python3 iterate through indexes
items=['baseball','basketball','football']
for index, item in enumerate(items):
print(index, item)
python3 iterate through indexes
items=['baseball','basketball','football']
for index, item in enumerate(items):
print(index, item)
python iterate through dictionary
a_dict = {'apple':'red', 'grass':'green', 'sky':'blue'}
for key in a_dict:
print key # for the keys
print a_dict[key] # for the values
named tuple python iterate
>>> a = A(1, 2)
>>> for name, value in a._asdict().iteritems():
print name
print value
a
1
b
2
>>> for fld in a._fields:
print fld
print getattr(a, fld)
a
1
b
2
python tuple iterate
You could google on "tuple unpacking". This can be used in various places in Python. The simplest is in assignment
>>> x = (1,2)
>>> a, b = x
>>> a
1
>>> b
2
In a for loop it works similarly. If each element of the iterable is a tuple, then you can specify two variables and each element in the loop will be unpacked to the two.
>>> x = [(1,2), (3,4), (5,6)]
>>> for item in x:
... print "A tuple", item
A tuple (1, 2)
A tuple (3, 4)
A tuple (5, 6)
>>> for a, b in x:
... print "First", a, "then", b
First 1 then 2
First 3 then 4
First 5 then 6
The enumerate function creates an iterable of tuples, so it can be used this way.
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us