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 trial

Python Python Comprehensions

Carlo DiCelico
seal-mask
.a{fill-rule:evenodd;}techdegree
Carlo DiCelico
iOS Development Techdegree Student 5,252 Points

Not 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]

Gotta love Python list comprehensions!

Iulia Maria Lungu
Iulia Maria Lungu
16,935 Points

i would upvote you if I could for this question @Carlo DiCelico

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

I 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
MOD
Chris Freeman
Treehouse Moderator 68,428 Points

To 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)]