+ 4
List Comprehensions Practice Help (Python)
My problem is to filter out all the vowels in the test case "hello", but my code prints the vowels, as well as the consonants, can someone please explain what I am doing wrong, and what to improve? Here's my code: word = input() print([i for i in word if word not in "aeiou"]) And here's the output: ['h', 'e', 'l', 'l', 'o'] Also, I don't completely understand the formula of list comprehensions, so if someone would explain that would be nice :)
11 Réponses
+ 8
... if i in ...
+ 6
Zohaib Sheikh
I will try to explain list comprehension formula.
print(SOMETHING for THE_ITEM in THE_SUBJECT if THE_ITEM meets the criteria)
+ 4
Zohaib Sheikh
something = expression
The formular without condition:
[expression for item in list]
e.g.
[i for i in word]
expression: i
item: i
list: word (word is a string but you can use it like a list)
It just puts every item of word into your new list
or if you have a list of numbers:
[n*2 for n in numbers]
expression: n*2
item: n
list: numbers
Here you multiply each item with two and put it in your new list
And the conditions comes at the end:
[expression for item in list if ...]
[i for i in word if i not in 'aeiou']
Here is a nice tutorial:
https://www.pythonforbeginners.com/basics/list-comprehensions-in-JUMP_LINK__&&__python__&&__JUMP_LINK
+ 4
This helps a lot, thank you so much! The expression makes so much sense now, I was confused perviously because it was the same as the item, but that isn’t always the case.
+ 3
Zohaib Sheikh
Btw: When you need an else part it is a bit different
[expression1 if-condition else expression2 for item in list]
nums = [1,2,3,4]
print(["even" if i % 2 == 0 else "odd" for i in nums])
+ 3
thats really interesting and helpful, thank you :)
+ 2
Thank you, Simon Sauter :)
+ 2
Rik Wittkopp
I do not understand the “SOMETHING for THE_Item” part
+ 2
The item is what I’m checking, but what is the “something”?
+ 2
Zohaib Sheikh
In case you want to store the item without any changes: expression = item
But the expression can be anything. Depending on what you want/need to store in your list.
A not so good example ;) but it shows what I mean:
word = "hello"
print( [True for i in word if i not in 'aeiou'])
output: [True, True, True]
+ 2
i see