5

I'm reading python cookbook, it mentioned that enumerate() returns an iterator yielding all the pairs(two -item tuples) of the form(index, item)

And I can use d=dict(enumerate(L)) to make a dict.

For my understanding, I thought enumerate() returns a tuple. And dict() can make a tuple into dict.

So I tried:

dict((1,2))

TypeError pops out.

So I'm wondering what object did enumerate actually returns here which dict() can make it into a dict?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Zen
  • 4,381
  • 5
  • 29
  • 56

2 Answers2

6

dict() constructor accepts an iterable sequence of key,value pairs.

Your snippet dict((1,2)) is not working because you are passing a tuple (1,2), one key,value pair. It iterates over (1,2) and finds integers while expecting sequences.

Instead you should have passed a tuple containing one pair:

>>> dict(((1,2),))
{1: 2}

Or, for example, a list:

>>> dict([[1,2]])
{1: 2}

enumerate() returns an enumerate object, which is an iterator over sequence of tuple pairs:

>>> enumerate(range(10))
<enumerate object at 0x1059b0f50>
>>> list(enumerate(range(10)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

Hope that makes things more clear to you.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • So, should I understand that enumerate returns something like ((0,item1))? – Zen Apr 04 '14 at 06:36
  • Besides, now I think I know how dict() works, it accept all kinds of paired data. Like [(1,2)] and even dict itself {1:2}. – Zen Apr 04 '14 at 06:37
  • @Zen good, enumerate returns an iterator over sequence of pairs - this is what dict accepts as an argument - that's why it works. – alecxe Apr 04 '14 at 12:54
1

It's its own type:

>>> type(enumerate([]))
<class 'enumerate'>
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79