newbie : removing recurring element from lists

CARbomboniere spa carbombo at libero.it
Fri Oct 11 05:50:48 EDT 2002


Hi,

How can I remove all occurences of a given value from a list ?
E.g. : I have a list like :

a = [1,4,5,1,3,1,5,1,1,6]

And I want to remove all the 1 values; so the output should be :

a = [4,5,3,5,6]


I tried the following two ways, neither of which works as expected :

-----------------------------------
# first way
a = [1,4,5,1,3,1,5,1,1,6]

x = 0
for t in a :
    if t == 1 :
        del a[x]
    x = x + 1

print a

---------------------------------

# second way
a = [1,4,5,1,3,1,5,1,1,6]

for t in a :
    if t == 1 :
        a.pop(t)

print a

---------

TIA.

Fabrizio





More information about the Python-list mailing list