5

I ran the following code in Python3.5.2 and got the corresponding output

>>> example = ['a','b','c','d','e']
>>> enumerate(example)
<enumerate object at 0x7f0211ea2360>

I'm unable to understand what is the meaning of this output.Why didn't the output come like this

 (0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e') 

When i used a list to contain these tuples the output was satisfactory

>>> list(enumerate(example))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

Note : I'm a newbie in python and when i posted this question i didn't know about map function so i didn't refer this question Why does map return a map object instead of a list in Python 3?

Community
  • 1
  • 1
Masquerade
  • 3,580
  • 5
  • 20
  • 37
  • 12
    because `enumerate` is an iterable. The values are generated on demand. – Jean-François Fabre Jan 12 '17 at 08:46
  • 2
    If you followed a tutorial based on Python 2, that may be the reason for your confusion: This behaviour has been introduced with Python 3. In that case, you should probably switch to a different tutorial. – Jonas Schäfer Jan 12 '17 at 08:51
  • 1
    Possible duplicate of [Why does map return a map object instead of a list in Python 3?](http://stackoverflow.com/questions/40015439/why-does-map-return-a-map-object-instead-of-a-list-in-python-3) (It's the same principle and answers discuss more generally than `map`) – Chris_Rands Jan 12 '17 at 08:53
  • @JonasSchäfer not for `enumerate`, no. It has always been a generator. – Jean-François Fabre Feb 15 '19 at 08:10

3 Answers3

11

That's purely a choice of design in Python 3 because enumerate is often used in loops/list comprehension, so no need to generate a full-fledged list and allocate memory for a temporary object which is very likely to be unused afterwards.

Most people use for i,e in enumerate(example): so they don't even notice the generator aspect, and the memory/CPU footprint is lower.

To get an actual list or set, you have to explicitly force the iteration like you did.

(note that as opposed to range, zip or map, enumerate has always been a generator, even in python 2.7, good choice from the start)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Understanding enumerate

Say train_ids is a list of my training object.

aa=enumerate(train_ids)
type(aa)
for i in aa:
    print(i)
khelwood
  • 55,782
  • 14
  • 81
  • 108
Noor
  • 11
  • 1
-3
l1 = ['a','b','c','d','e']
for i in enumerate(l1):
   print i
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
viki
  • 1
  • 1