Consider this:
the_data = ['a','b','c']
With enumerate this loop can be written as:
for index,item in enumerate(the_data):
# index = 1 , item = 'a'
If the_data = { 'john':'football','mary':'snooker','dhruv':'hockey'}
Loop with key value pair assigned in loop:
for name,sport in the_data.iteritems():
#name -> john,sport-> football
While using enumerate, the data becomes a tuple within the loop, hence needs one extra line of assignment after the loop declaration :
#can assignment of name & sport happen within the `for-in` line itself ?
for index,name_sport_tuple in enumerate(the_data.iteritems()):
name,sport = name_sport_tuple # Can this line somehow be avoided ?
#index-> 1,name-> john, sport -> football
Use this:
for index, (name, sport) in enumerate(the_data.iteritems()):
pass
This is equivalent to:
>>> a, (b, c) = [1, (2, 3)]
>>> a, b, c
(1, 2, 3)
This is commonly used with zip
and enumerate
combo as well:
for i, (a, b) in enumerate(zip(seq1, seq2)):
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With