There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
Agree with a comment or answer? Like () to up-vote the contribution!
Hello, @markeko, and welcome to the forums. That is not the correct syntax for a list comprehension. When you want to use if..else in a comprehension the syntax should resemble this trivial example:
import string
alphabet = string.ascii_lowercase
print(alphabet)
only_vowels = [letter if letter in 'aeiou' else '*' for letter in alphabet]
print(''.join(only_vowels))
nums = [4, 8, 15, 16, 23, 42]
parity = [x%2 for x in nums]
How do you print out odd numbers and even number of the list?
Is if else statement required here?
For your list comprehension that does indeed seem like the easiest way to do it. You’re looking to filter out values which are not odd. So you’d need a logical statement with a True/False response as to whether or not a particular integer was odd. As an example here’s a rather useless piece of code for creating a list of all numbers 0 through to and including 9 but only if they equal 3 via list comprehension-
I’m not certain as sometimes the testing can be rather strict in its requirements. It may be worth altering your comprehension to return integers instead of strings.