Difference between list() and dict() with generators

521 views Asked by At

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}
3

There are 3 answers

0
filmor On BEST ANSWER

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.

0
Daniel Roseman On

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.

0
Tanveer Alam On

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.