Enumerate means to "mention a list of items, one by one." So, it would be most useful in loops over a list.
The built in enumerate() function lists the items in a list along side their index number:
order_list = ['fist', 'second', 'third']
for i in enumerate(order_list):
print i
(0, 'fist')
(1, 'second')
(2, 'third')
This is useful for getting the index values of a list:
for i, order in enumerate(order_list):
print i, order
0 fist
1 second
2 third
Thus, this function is a better way of looping over a certain list:
for i in range(len(order_list)):
print i, order_list[i]
0 fist
1 second
2 third
Why is enumerate() better than range(len())? Because it is one function instead of two nested functions!
You may also iterate through each item of a list without a loop by using the next function:
items = enumerat(order_list)
items.next()
items.next()
items.next()
See more here: http://www.juniordevelopercentral.com/python-enumerate-function/
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.