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


Difference between using tuples and lists in comprehensions?

For example using a string works all good and gives the desired output.

```nums = range(1, 101)

fizzbuzz = {'fizz':[n for n in nums if n % 3 == 0], 'buzz':[n for n in nums if n % 7 == 0]}```

but using a tuple like this

fizzbuzz = {'fizz':(n for n in nums if n % 3 == 0), 'buzz':(n for n in nums if n % 7 == 0)}

returns this

{'fizz': <generator object <genexpr> at 0x1041ea518>, 'buzz': <generator object <genexpr> at 0x1041ea570>}

any idea what the difference is?

1 Answer

Schaffer Robichaux
Schaffer Robichaux
21,729 Points

Hey Tyler,

  • In your first example, fizzbuzz, your for __ in for fizz and buzz is set in brackets [] which is an example of list comprehension thereby giving you the expected results

  • In your second example, fizzbuzz2, your for__in loops are set in () which is an example of a generator expression.

  • You can achieve the same results in fizzbuzz2 by applying the list() method to your generator expression values

fizzbuzz2 = {'fizz':list((n for n in nums if n % 3 == 0)), 'buzz':list((n for n in nums if n % 7 == 0))}

The most popular answer at this stackoverflow link provides good insight into the subject.

Hope that helped