Python @ DjangoSpin

Python: Enumerating with enumerate()

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

enumerate() in Python

enumerate() in Python

It is sometimes needed to have an index counter for elements of an iterable object. Python's builtin enumerate class enables us to do just this. The constructor of builtin enumerate class accepts an iterable object and returns an iterator of tuples in the form (index, value).

>>> help(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]), ...
...

### EXAMPLE ###
>>> listOne = [ 'apple', 'ball', 'cat', 'dog' ]
>>> enumeratedObject = enumerate(listOne)
>>> next(enumeratedObject)
(0, 'apple')
>>> next(enumeratedObject)
(1, 'ball')



# Using a for loop to iterate over the iterator of tuples
>>> listOne = [ 'apple', 'ball', 'cat', 'dog' ]
>>> for pair in enumerate(listOne):
	print(pair)

	
(0, 'apple')
(1, 'ball')
(2, 'cat')
(3, 'dog')



# Unpacking the tuples
>>> listOne = [ 'apple', 'ball', 'cat', 'dog' ]
>>> for index, element in enumerate(listOne):
	print(index, ": ", element)

	
0 :  apple
1 :  ball
2 :  cat
3 :  dog

By default, the indexes start from 0. To alter this, Python provides us with an optional second argument, which tells the enumerate class to begin indexes from the specified value.

>>> listOne = [ 'apple', 'ball', 'cat', 'dog' ]
>>> for index, element in enumerate(listOne, start = 1):
	print(index, ": ", element)

	
1 :  apple
2 :  ball
3 :  cat
4 :  dog

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply