Python problem

Discussion in 'Python' started by WIWA, Aug 18, 2003.

  1. WIWA

    WIWA Guest

    Hi all,



    I'm trying to write the following in python:



    j=0

    for i in range(len(datumlijst)+1):

    if (datumlijst[i+1]!=datumlijst):

    datum[j]=datumlijst

    j=j+1



    print datum[:]



    it complains about the part: datumlijst[i+1]!=datumlijst



    it produces the following error:



    File "hits_per_dag.py", line 24, in ?

    datum[j]=datumlijst

    IndexError: list assignment index out of range



    Anyone know why this happens


    --
    Posted via http://dbforums.com
     
    WIWA, Aug 18, 2003
    #1
    1. Advertising

  2. WIWA

    Peter Otten Guest

    WIWA wrote:
    >
    > I'm trying to write the following in python:


    > j=0
    >
    > for i in range(len(datumlijst)+1):
    > if (datumlijst[i+1]!=datumlijst):
    > datum[j]=datumlijst
    > j=j+1


    > print datum[:]
    >
    > it complains about the part: datumlijst[i+1]!=datumlijst
    >

    You are comparing a list with a list entry which is probably unintended.

    > datum[j]=datumlijst
    >
    > IndexError: list assignment index out of range
    >

    You seem to assume that a list grows automatically. That's not true in
    Python.

    Now here's my guess of your intentions:

    datumlijst = [1,1,2,2,3,4,5,5,5,5,6,3]
    datumlijst.sort()
    datum = [datumlijst[0]]

    for i in range(len(datumlijst)-1): # all list indexes start with 0
    if datumlijst[i+1] != datumlijst: # both indexed
    datum.append(datumlijst[i+1]) # note the append()

    print datum #no need for [:]

    There may still sit a bug in the above. The following should be a little
    more robust, e. g. no need to sort datumlijst, no extensive use of list
    indexes:

    from sets import Set
    datumlijst = [1,1,2,2,3,4,5,5,5,5,6,3]
    print list(Set(datumlijst))

    This is Python 2.3 only, in 2.2 you can do it with a dictionary, using the
    keys only.

    Peter

    PS: I see you've already fallen in love with whitespace :)
     
    Peter Otten, Aug 18, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    0
    Views:
    751
  2. Paul Moore
    Replies:
    0
    Views:
    619
    Paul Moore
    Mar 1, 2008
  3. Martin v. Löwis
    Replies:
    0
    Views:
    661
    Martin v. Löwis
    Mar 1, 2008
  4. Senthil Kumaran
    Replies:
    0
    Views:
    580
    Senthil Kumaran
    Jan 17, 2011
  5. R. David Murray
    Replies:
    0
    Views:
    761
    R. David Murray
    Jan 17, 2011
Loading...

Share This Page