+ 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 :)

17th Jan 2022, 9:45 PM
Zohaib Sheikh
11 Réponses
+ 8
... if i in ...
17th Jan 2022, 9:54 PM
Simon Sauter
Simon Sauter - avatar
+ 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)
17th Jan 2022, 10:18 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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
17th Jan 2022, 11:01 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
17th Jan 2022, 11:09 PM
Zohaib Sheikh
+ 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])
18th Jan 2022, 12:02 AM
Denise Roßberg
Denise Roßberg - avatar
+ 3
thats really interesting and helpful, thank you :)
18th Jan 2022, 2:44 AM
Zohaib Sheikh
+ 2
Thank you, Simon Sauter :)
17th Jan 2022, 9:57 PM
Zohaib Sheikh
+ 2
Rik Wittkopp I do not understand the “SOMETHING for THE_Item” part
17th Jan 2022, 10:33 PM
Zohaib Sheikh
+ 2
The item is what I’m checking, but what is the “something”?
17th Jan 2022, 10:34 PM
Zohaib Sheikh
+ 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]
17th Jan 2022, 11:37 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
i see
18th Jan 2022, 2:44 AM
Zohaib Sheikh