Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Python Comprehensions!
You have completed Python Comprehensions!
Preview
We’ve just learned how to turn simple loops into a 1-line list comprehension. But what about loops that have conditional if/else blocks? List comprehension can handle that too!
The Syntax
# Condition affects the list
[expression for temp_var in iterable if condition]
# Condition affects the expression
[expression if condition else expression for temp_var in iterable]
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
But what about loops that have
conditional if else blocks?
0:00
List comprehensions can handle that too.
0:01
There are two types of conditional list
comprehension syntaxes, and it depends on
0:04
whether the conditional effects the
iterable, or if it affects the expression.
0:09
When a conditional affects the iterable,
0:14
the number of elements of the iterable
might change based on the condition.
0:17
Taking our welcome banner, for example,
0:22
we might want to filter out any letter
that isn't a vowel from the final string.
0:25
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up