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?
Asked
Active
Viewed 63 times
0

Bikramjeet Singh
- 681
- 1
- 7
- 22

Roy
- 31
- 3
2 Answers
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
-
Correction in second code: only = [item for item in l if item in filters] – Bikramjeet Singh Dec 14 '19 at 16:28
-
Thank you very much, I ended up doing: l = l[1]. – Roy Dec 14 '19 at 18:01
-
@Roy well no problem, but your answer is very specific for this list, you want to do more generic stuff, also consider makr my answer as currect if you thing so :) – Reznik Dec 14 '19 at 22:50
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
-
-
Your solution perfectly suits for his question. I just gave another option. – Prince Francis Dec 14 '19 at 16:23
-
But your option is worng, consider there is two `world` in this list, its going to give me only one of them in a list... `['world', 'world']` would return `['world']` – Reznik Dec 14 '19 at 16:24
-
I updated my answer, to fit for that scenario. Thanks for noticing it. – Prince Francis Dec 14 '19 at 16:25
-
-
In case that hint wasn't big enough: I think it would be better if you removed three lines. – Stefan Pochmann Dec 15 '19 at 15:04
-
I didn't catch the hint. You are welcome to edit my answer. As I am learning python, it would be a help for me. – Prince Francis Dec 16 '19 at 05:04