Possible Duplicate:
Remove items from a list while iterating in Python
I'm trying to remove an item from a list in python:
x = ["ok", "jj", "uy", "poooo", "fren"] for item in x: if len(item) != 2: print "length of %s is: %s" %(item, len(item)) x.remove(item)
But it doesn't remove "fren"
item. Any ideas?
You can make use of a for-loop that we will traverse the list of items to remove duplicates. The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given.
You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set. You must convert the dictionary or set back into a list to see a list whose duplicates have been removed.
You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:
y = [s for s in x if len(s) == 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With