Python Challenge - FizzBuzz, FizzBuzz

This community-built FAQ covers the “FizzBuzz” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge FizzBuzz

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

def fizzbuzz(limit):
    a = [*range(1, int(limit + 1))]
    return "Input Error!"
  for x in range(2, len(a), 3):
    a[x] = 'Fizz'
  if limit < 5: return a
  for x in range(4, len(a), 5):
    a[x] = 'Buzz'
  if limit < 15: return a
  for x in range(14, len(a), 15):
    a[x] = 'FizzBuzz' 
  return a

If I were to rank this question, it’d be “easy”, not “intermediate”, which is what it is labeled as at the time of writing.
Since we’re tasked to return a list of the length of the input, the most optimal solution must scale with the size of the input number.
How you iterate through building the list, is up to your preference. Personally, I simply used modulus for the “Fizz” “Buzz” and “FizzBuzz” scenarios and appended the value or appropriate string to a list. Then output the built list. The hardest part (to me) was simply remembering how range worked to account for the list starting at 1 and including the number provided. Lists of length 5, for example, normally have indices from 0-4 so thats how range’s defaults rightfully work.

def fizzbuzz(limit): # Write your code here new_list = [] for i in range(1, limit+1): if (i % 3 == 0) & (i % 5 == 0): new_list.append("FizzBuzz") elif i % 3 == 0: new_list.append("Fizz") elif i % 5 == 0: new_list.append("Buzz") else: new_list.append(i) return new_list print(fizzbuzz(16))

Did you do complete this challenge and pass all the tests? How about posting your code?

def fizzbuzz(limit): result = [] for i in range(1, limit + 1): val = '' if not i % 3: val += "Fizz" if not i % 5: val += "Buzz" if not val: val = i result.append(val) return result print(fizzbuzz(25)) def fizzbuzz2(limit): return ['FizzBuzz' if not i % 15 else 'Buzz' if not i % 5 else 'Fizz' if not i % 3 else i for i in range (1, limit + 1)] print(fizzbuzz2(25))

I did pass all the tests, but didn’t post the code because of the forums prompt suggested to “Help the user learn to troubleshoot.” So I chose to go about describing factors of a possible solution and then give feedback on the difficulty level compared so the many other code challenge sites available. :smiley:
I like that your solution, @mtf, approached the problem differently than I did. If I’m not mistaken, you build a list without the special cases and then go back and replace the values for those cases. The error handling is a good idea too. In interviews, I usually ask if I should bother with error handling or go straight for the solution assuming the input is within expected bounds.

My solution was a lot like @kirklandgee982867953. I think an optimization analysis between the two would be an interesting dive under the hood of python, though probably not meaningful enough to warrant a “winner”, not that this is a competition.
What is more “expensive” - 1) The re-building of arrays under the hood to accommodate the fact that lists are not of a fixed length.
2) Building the list first then going back and replacing the indexes that meet the special cases.
Without putting TOO much thought into it, I’d say 2 becomes faster than 1 as the input grows since the rebuilding of the arrays (as described) under the hood would potentially create something similar to an NlogN type complexity or worse. I could be totally wrong but thats my quick, 30-second thought process about it. haha

1 Like

The method was chosen because, a) there are no conditionals, and, b) The iterations are quick since we leap from point to point and only mutate those points. In all, less than half of the elements are mutated. All this is done in place. For me it was just novel, and a different approach than the one normally reached for.

The thing to do to test the speed would be create a list with a million elements and test both cases. the fixed list with mutations vs the growing list with conditionals. My bet is the former will be faster.

Proposal :

def fizzbuzz(limit):
return [ [i,‘Fizz’,‘Buzz’,‘FizzBuzz’ ][(i%3==0) + (i%5==0)*2] for i in range(1,limit+1)]


1 Like

Very nice; again, without conditionals. Love the list index approach, one I’ve been playing with in recent times in some other problems.

def fizzbuzz(limit):
l_limit=[ x for x in range(1,limit+1)]
for i in range((len(l_limit))):
if l_limit[i]%3==0 and l_limit[i]%5!=0:
elif l_limit[i]%3!=0 and l_limit[i]%5==0:
elif l_limit[i]%3==0 and l_limit[i]%5==0:
return l_limit

You ready for pain?

def fizzbuzz(limit): return ["FizzBuzz" if x%5==0 and x%3==0 else "Fizz" if x%3==0 else "Buzz" if x%5==0 else x for x in range(1, limit+1)] print(fizzbuzz(16))
def fizzbuzz(n): fizz_list = [] for num in range(1,n+1): if num % 3 == 0 and num % 5 == 0: fizz_list.append('FizzBuzz') elif num % 3 == 0: fizz_list.append('Fizz') elif num % 5 == 0: fizz_list.append('Buzz') else: fizz_list.append(num) return fizz_list print(fizzbuzz(16))

My first instinct was to create a list using the built-in range function, then to loop through each number in the list and change those that were multiples of 3 and/or 5 using the modulo operator. This didn’t quite work like I’d expected it to. The list that I created using the range function seems to be immutable. To see what I mean, try running the code below. Uncomment the print statements to convince yourself that the list remains unchanged from the time that it’s created.

def fizzbuzz(limit): numlist = list(range(1, (limit + 1))) # print(numlist) for num in numlist: if (num % 3) == 0 and (num % 5) == 0: num = 'FizzBuzz' elif (num % 3) == 0: num = 'Fizz' elif (num % 5) == 0: num = 'Buzz' # print(numlist) return numlist print(fizzbuzz(16))

I couldn’t figure out why the above didn’t work, but didn’t want to look up any info about it until after I’d completed the challenge. Refer to the very end of this post to see why it didn’t work.

So my next attempted strategy was to build the final list, one element at a time. This is my favored solution.

def fizzbuzz(limit): counter = 1 numlist = [] while counter <= limit: if counter % 3 == 0 and counter % 5 == 0: numlist.append('FizzBuzz') elif counter % 3 == 0: numlist.append('Fizz') elif counter % 5 == 0: numlist.append('Buzz') else: numlist.append(counter) counter += 1 return numlist print(fizzbuzz(16))

The above solution works well. I believe, though, that you can make the code a bit more efficient performance-wise by reducing the number of times the “% 3” operation is performed, as shown below. But the greater efficiency is, in my opinion, at the expense of readability.

def fizzbuzz(limit): counter = 1 numlist = [] while counter <= limit: if counter % 3 == 0: if counter % 5 == 0: numlist.append('FizzBuzz') else: numlist.append('Fizz') elif counter % 5 == 0: numlist.append('Buzz') else: numlist.append(counter) counter += 1 return numlist print(fizzbuzz(16))

The reason my first approach didn’t work is covered fairly well in this StackOverflow post.

Check out the answer from alandarev. He says:

for element in li - returns you a copy of element, not the element itself."

We can test this out as shown below. Print the list element before and after trying to modify it. We can see that the list element num from the loop iteration is indeed being modified, but the list numlist is not being modified. This seems to verify that what user, alandarev, from stackoverflow said is true: num is simply a copy of each element in the list, and modifying it does not modify the original list element.

def fizzbuzz(limit): numlist = list(range(1, (limit + 1))) for num in numlist: print(num) if (num % 3) == 0 and (num % 5) == 0: num = 'FizzBuzz' elif (num % 3) == 0: num = 'Fizz' elif (num % 5) == 0: num = 'Buzz' print(num) print("") return numlist print(fizzbuzz(16))

The same stackoverflow thread mentions various methods for modifying list elements so as to make this general solution strategy viable.

for num in numlist:

We sometimes refer to this as read-only since we cannot mutate the list in this loop. The indices must be exposed if we are to mutate the list.

def fizzbuzz(limit): f = lambda n, s, m: s if n % m == 0 else "" return [(f(n, "Fizz", 3) + f(n, "Buzz", 5)) or n for n in range(1, limit + 1)] print(fizzbuzz(16))
1 Like
def fizzbuzz(n): l=[] for i in range(1,n+1): if (i%3==0) and (i%5==0): l.append("FizzBuzz") elif i%5==0: l.append("Buzz") elif i%3==0: l.append("Fizz") else: l.append(i) return(l) print(fizzbuzz(16))
def fizzbuzz(limit):
  init_list = []
  index = 0
  for i in range(1,limit+1):
  for i in init_list:
    if i%3 == 0 and i%5 !=0:
        init_list[index] = "Fizz"
    elif i%5 == 0 and i%3!=0:
        init_list[index] = "Buzz"
    elif i%3 == 0 and i%5 == 0:
      init_list[index] = "FizzBuzz"
    index = index + 1
  return init_list


def fizzbuzz(limit): L = [] for i in range (1, limit + 1): L.append(i) for j in range (len(L)): num = L[j] if num % 3 == 0: L[j] = "Fizz" if num % 5 == 0: L[j] = "Buzz" if num % 5 == 0 and num % 3 == 0: L[j] = "FizzBuzz" return L print(fizzbuzz(16))
msg = { 6: "Fizz", 10: "Buzz", 0: "FizzBuzz" }
def fizzbuzz(limit):
  return [msg.get(i ** 4 % 15, i) for i in range(1, limit + 1)]
1 Like