advanced listcomprehenions?

Gabriel Genellina gagsl-py2 at
Thu Jun 19 00:55:16 CEST 2008

En Wed, 18 Jun 2008 18:42:00 -0300, cirfu <circularfunc at> escribió:

> I am wondering if it is possible to write advanced listcomprehensions.
> For example:
> """Write a program that prints the numbers from 1 to 100. But for
> multiples of three print "Fizz" instead of the number and for the
> multiples of five print "Buzz". For numbers which are multiples of
> both three and five print "FizzBuzz"."""
> Obv it doesnt have to be a list according tot hat definition but
> suppose i want to generate that list.

Go to and search for "fizz  

> or to generate a lisrt but not by listcomprehsnion:
> map(lambda x: (not x%3 and not x%5 and "FizzBuzz") or (not x%3 and
> "Fizz")
> or (not x%5 and "Buzz") or x, xrange(1,101))

You can translate that into a list comprehension - in general, map(f,  
items) is the same as [f(x) for x in items]. We have then:

[(not x%3 and not x%5 and "FizzBuzz") or (not x%3 and "Fizz") or (not x%5  
and "Buzz") or x for x in xrange(1,101)]

Quite unreadable IMHO. Just to add another variant to the zillion ones  
already posted:

def fb(x):
   mult3 = x%3 == 0
   mult5 = x%5 == 0
   if mult3 and mult5: return "FizzBuzz"
   elif mult3: return "Fizz"
   elif mult5: return "Buzz"
   return str(x)

[fb(x) for x in range(1,101)]

Gabriel Genellina

More information about the Python-list mailing list