Python problem

Peter Otten __peter__ at web.de
Mon Aug 18 13:24:09 EDT 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
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[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
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 :-)




More information about the Python-list mailing list