Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove item from a python list in a loop? [duplicate]

Tags:

python

list

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?

like image 419
alwbtc Avatar asked Nov 29 '11 14:11

alwbtc


People also ask

How do you remove duplicates from a list in a loop in Python?

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.

How do you remove a duplicate character from a list in Python?

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.


1 Answers

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] 
like image 166
Sven Marnach Avatar answered Sep 23 '22 01:09

Sven Marnach