LearnFrenzy
Sign in Take a free test

List Comprehensions · List Comprehensions Coding Problems · Question 1

FizzBuzz in a single list comprehension in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Build the FizzBuzz sequence from 1 to 15 with one list comprehension.

Solution
main.py Run
fb = ["FizzBuzz" if n % 15 == 0 else "Fizz" if n % 3 == 0 else "Buzz" if n % 5 == 0 else n
      for n in range(1, 16)]
print(fb)

Output Verified by running it on Python 3

[1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz']

A chained conditional expression chooses the value for every n, so no item is filtered out. The combined case is tested first.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links