Reputation: 167
I have been trying to figure out how to find specific words in a list then move these to a new list. Say i have :
a = ['a','b','c','d','e']
and I only want to have a, c and e. Is it possible to do this without using .remove() ?
Upvotes: 2
Views: 1201
Reputation: 387
Well, I hope I understood your question right. You want to only select the contents of one list if they are in another list. You might use list comprehensions.
Here's an example playing at the interactive prompt.
>>> a = ['a','b','c','d','e']
>>> [x for x in a if x in ['a', 'c', 'e' ]]
['a', 'c', 'e']
or with clearer naming
>>> list = ['a','b','c','d','e', 'a', 'd', 'e', 'c']
>>> wanted = ['a', 'c', 'e' ]
>>> [x for x in list if x in wanted]
['a', 'c', 'e', 'a', 'e', 'c']
Upvotes: 4
Reputation: 32580
Use the filter()
builtin function:
>>> lst = ['a','b','c','d','e']
>>>
>>> def keep(item):
... # Implement whatever criterion you need here
... return item in ('a', 'c', 'e')
...
>>> filter(keep, lst)
['a', 'c', 'e']
filter
will simply return a filtered sequence (a list in your case) without modifying the input sequence.
keep
in this example just needs to be a function that, given an item, decides whether to keep it or not by returning True
(keep) or False
(discard).
Note: As pointed out by @tobias_k, in Python 3 filter()
will return an iterator. So if you actually do need a list (not just an iterable), you'd need to pass it to the list()
constructor like this:
newlist = list(filter(keep, lst))
Upvotes: 3