Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialCarlo DiCelico
iOS Development Techdegree Student 5,252 PointsNot putting else in your list comprehension
fizzbuzz = [ 'Fizzbuzz' if num % 15 == 0 else
'Fizz' if num % 3 == 0 else
'Buzz' if num % 5 == 0 else
num for num in range (1, 101) ]
This is actually (a) allowed, (b) elegant and readable, and (c) a lot like pattern matching in other languages.
[edit: Added python formatting -cf]
Iain Simmons
Treehouse Moderator 32,305 PointsGotta love Python list comprehensions!
Iulia Maria Lungu
16,935 Pointsi would upvote you if I could for this question @Carlo DiCelico
2 Answers
Kenneth Love
Treehouse Guest TeacherI actually find that difficult to read. It could probably be tackled a cleaner way outside of a comprehension.
That said, yes, you can use else
in a comprehension. You can't use it (at least in my experience, research, and testing) like you do in a "ternary" operation name = "Kenneth" if a < 2 else "Bob"
.
But, yeah, once your list comp breaks 2 lines, you should probably find another solution.
Chris Freeman
Treehouse Moderator 68,441 PointsTo answer Kennethβs challenge:
def fizz_or_buzz(num):
if num % 15 == 0:
return 'Fizzbuzz'
elif num % 3 == 0:
return 'Fizz':
elif num % 5 == 0:
return 'Buzz'
else:
return num
fizzbuzz = [fizz_or_buzz(nun) for num in range (1, 101)]
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsNice example!