0

Let's say I have this list: list = ['hello','world','spam','eggs'] and I want to clear everything from that list EXCEPT 'world'. How do I do this?

Bikramjeet Singh
  • 681
  • 1
  • 7
  • 22
Roy
  • 31
  • 3

2 Answers2

4

You can use list comprehension for this as:

l = ['hello','world','spam','eggs']
only = [item for item in l if item  == 'world'] # ['world']

if you want to do it for multiple words you can store you filters as this:

l = ['hello','world','spam','eggs']
filters = ['hello', 'world']
only = [item for item in l if item  in filters] # ['hello', 'world']

or you can also use the filter function as this:

l = ['hello','world','spam','eggs']
only = filter(lambda x: x == 'hello', l) # ['hello']

In totaly, consider now to call your varibles by the type name, calling something list override the list constructor, which can lead for other prolbems in the future

Reznik
  • 2,663
  • 1
  • 11
  • 31
1

another solution is to check if 'world' exists in your list. If not assign an empty list.

list = ['hello','world','spam','eggs']
if 'world' in list:
    list = ['world'] * list.count('world')
else:
    list = []
print(list)
Prince Francis
  • 2,995
  • 1
  • 14
  • 22