In this lesson, you’ll learn how to use range()
and enumerate()
to solve the classic interview question known as Fizz Buzz.
range()
is a built-in function used to iterate through a sequence of numbers. Some common use cases would be to iterate from the numbers 0 to 10:
>>> list(range(11))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
To learn more, check out The Python range() Function.
enumerate()
is a built-in function to iterate through a sequence and keep track of both the index and the number. You can pass in an optional start parameter to indicate which number the index should start at:
>>> list(enumerate([1, 2, 3]))
[(0, 1), (1, 2), (2, 3)]
>>> list(enumerate([1, 2, 3], start=10))
[(10, 1), (11, 2), (12, 3)]
To learn more, check out Use enumerate() to Keep a Running Index.
Here’s the solution in the video:
for i, num in enumerate(numbers):
if num % 3 == 0:
numbers[i] = "fizz"
if num % 5 == 0:
numbers[i] = "buzz"
if num % 5 == 0 and num % 3 == 0:
numbers[i] = "fizzbuzz"
You could also solve the question using only one if
condition:
for i, num in enumerate(numbers):
if num % 5 == 0 and num % 3 == 0:
numbers[i] = "fizzbuzz"
elif num % 3 == 0:
numbers[i] = "fizz"
elif num % 5 == 0:
numbers[i] = "buzz"
Both are valid. The first solution looks more similar to the problem description, while the second solution has a slight optimization where you don’t mutate the list potentially three times per iteration.
In the video, you saw the interactive Python Terminal iPython. It has color coating and many useful built-in methods. You can install it.
James Uejio RP Team on April 27, 2020
I use the interactive Python Terminal iPython. It has color coating and many useful built in methods. You can install it here.