Python problem

Peter Otten __peter__ at
Mon Aug 18 19:24:09 CEST 2003

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

Now here's my guess of your intentions:

datumlijst = [1,1,2,2,3,4,5,5,5,5,6,3] 
datum = [datumlijst[0]]

for i in range(len(datumlijst)-1): # all list indexes start with 0
    if datumlijst[i+1] != datumlijst[i]: # 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

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.


PS: I see you've already fallen in love with whitespace :-)

More information about the Python-list mailing list