user2935002
user2935002

Reputation: 79

Confused by the enumerate() function in tutorials

Actually I am learning python with some previously written scripts, I try to understand codes lines by line but in this code I don't know what exactly is going on (specially in line 2):

def convertSeq(s, index):
    result = [i + 1 for i, ch in enumerate(s) if ch == '1']
    result = ' '.join([str(index) + ':' + str(i) for i in result])
    result = str(index) + ' ' + result
    return result

thanks

Upvotes: 1

Views: 142

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

enumerate returns an iterator(enumerate object), which yields tuples containing index and item from the iterable/itertator passed to it.

>>> text = 'qwerty'
>>> it = enumerate(text)
>>> next(it)
(0, 'q')
>>> next(it)
(1, 'w')
>>> next(it)
(2, 'e')
>>> list(enumerate(text))
[(0, 'q'), (1, 'w'), (2, 'e'), (3, 'r'), (4, 't'), (5, 'y')]

So, the list comprehension in your code is actually equivalent to:

>>> text = '12121'
>>> result = []
for item in enumerate(text):
    i, ch = item              #sequence unpacking
    if ch == '1':
        result.append(i+1)
...         
>>> result
[1, 3, 5]

In fact you can also pass the starting point of the index to the enumerate, so your list comprehesion can be changed to:

result = [i for i, ch in enumerate(s, start=1) if ch == '1']

enumerate is usually preferred over something like this:

>>> lis = [4, 5, 6, 7]
for i in xrange(len(lis)):
    print i,'-->',lis[i]
...     
0 --> 4
1 --> 5
2 --> 6
3 --> 7

Better:

>>> for ind, item in enumerate(lis):
    print ind,'-->', item
...     
0 --> 4
1 --> 5
2 --> 6
3 --> 7

enumerate will work on iterators as well:

>>> it = iter(range(5, 9))      #Indexing not possible here
for ind, item in enumerate(it):
    print ind,'-->', item
...     
0 --> 5
1 --> 6
2 --> 7
3 --> 8

Help on enumerate:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

Upvotes: 1

Alexander Zhukov
Alexander Zhukov

Reputation: 4557

enumarate is a python built-in function to help you to keep track of the indexes of the sequence.

See the following code:

    >>>sequence = ['foo', 'bar', 'baz']
    >>>
    >>>list(enumerate(sequence)) # prints [(0, 'foo'), (1, 'bar'), (2, 'baz')]
    >>>
    >>>zip(range(len(sequence)), sequence) # prints [(0, 'foo'), (1, 'bar'), (2, 'baz')]
    >>>for item in sequence:
    ......print (item, sequence.index(item))
    ('foo', 0)
    ('bar', 1)
    ('baz', 2)

As you can see, the results are the same, but with enumerate it is easier to write, read and it is more efficient in some cases.

Upvotes: 0

Chris Taylor
Chris Taylor

Reputation: 47402

It creates a new iterator from any iterable object, which returns the values in the original object, together with an index starting from 0. For example

lst = ["spam", "eggs", "tomatoes"]

for item in lst:
  print item

# spam
# eggs
# tomatoes

for i, item in enumerate(lst):
   print i, item

# 0 spam
# 1 eggs
# 2 tomatoes

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43245

enumerate iterates over an iterator, and returns a tuple with current index and the current item.

>>> for i in range(100,105):
...     print(i)
... 
100
101
102
103
104
>>> for info in enumerate(range(100,105)):
...     print(info)
... 
(0, 100)
(1, 101)
(2, 102)
(3, 103)
(4, 104)

Upvotes: 0

Related Questions