newbie : removing recurring element from lists

Andrew Thompson andrew.thompson at ashecastle.com
Fri Oct 11 06:03:45 EDT 2002


Your problem lies in the fact that as you delete members of your list,
the list itself changes, but your loops expect the list to be the same
size as when they started...

Much better to let the machine do the work :
'

while aList.__contains__(yourValue):
	aList.remove(yourValue)

'

Andrew

-----Original Message-----
From: python-list-admin at python.org [mailto:python-list-admin at python.org]
On Behalf Of CARbomboniere spa
Sent: 11 October 2002 10:51
To: python-list at python.org
Subject: newbie : removing recurring element from lists

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


-- 
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list