1

For some reason IDLE is not displaying the type of tuple i. Any idea what's wrong here?

IDLE (Python)

>>> d = {"a":"apple","b":"boy","c":"cat"}
>>> d
{'a': 'apple', 'b': 'boy', 'c': 'cat'}
>>> t = ((k,v) for k,v in d.items())
>>> t
<generator object <genexpr> at 0x0237C558>
>>> for i in t: print(i)

('a', 'apple')
('b', 'boy')
('c', 'cat')
>>> for i in t: print(type(i))

>>> 
Patt Mehta
  • 4,110
  • 1
  • 23
  • 47

2 Answers2

2

You can consume Iterator / Generator only one time.

>>> a = [1,2,3]
>>> g = iter(a)
>>> for i in g: print i
...
1
2
3
>>> for i in g: print i
...
>>>
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • >>> a = [1,2] >>> for i in a: print(i) # 1 2 >>> for i in a: print(i) # 1 2 How is this different? – Patt Mehta Aug 30 '13 at 14:02
  • @GLES, `for i in a: ..` is similar to `for i in iter(a): ..` which create new iterator. If you do another `for i in a`, it will create another iterator instead of using already consumed one. – falsetru Aug 30 '13 at 14:04
2

Generators are iterators but they do not store data into memory like lists so they can be accessed only once.
Here is a great explanation about generators.

Community
  • 1
  • 1
xor
  • 2,668
  • 2
  • 28
  • 42
  • http://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension 8) My intent was to create a tuple comp'n – Patt Mehta Aug 30 '13 at 14:23