1

So what's the explanation behind the difference between list() and dict() in the following example:

glist = (x for x in (1, 2, 3))
print(list(glist))
print(list(glist))

gdict = {x:y for x,y in ((1,11), (2,22), (3,33))}
print(dict(gdict))
print(dict(gdict))

>>>
[1, 2, 3]
[]
{1: 11, 2: 22, 3: 33}
{1: 11, 2: 22, 3: 33}
Basel Shishani
  • 7,185
  • 6
  • 47
  • 65
  • 1
    read http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension for more info – Mazdak Jun 09 '15 at 07:27

3 Answers3

3

The difference is that only the first expression glist is a generator, the second one gdict is a dict-comprehension. The two would only be equivalent, if you'd change the first one for [x for x in (1, 2, 3)].

A comprehension is evaluated immediately.

filmor
  • 28,551
  • 4
  • 47
  • 46
1

These are completely different things. The first expression is a generator: after the first iteration, it is exhausted, so further iterations are empty.

The second is a dict comprehension: like a list comprehension, it returns a new object each time, in this case a dict. So each iteration is over a new dict.

Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842
0

An example would be better to understand this.

Calling next method of generator to yield each element.

>>> a = (i for i in range(4))
>>> a.next()
0
>>> a.next()
1
>>> a.next()
2
>>> a.next()
3
>>> a.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
>>> list(a)
[]

Now calling list function on our generator object.

>>> a = (i for i in range(4))
>>> list(a)
[0, 1, 2, 3]
>>> list(a)
[]

Now calling list on our list comprehension.

>>> a = [i for i in range(4)]
>>> list(a)
[0, 1, 2, 3]
>>> list(a)
[0, 1, 2, 3]

So list comprehension and dict comprehension are similar which results in actual data not like generator which yields element.

Tanveer Alam
  • 4,987
  • 3
  • 20
  • 41