When the data acquired by the loop is a tuple, multiple variables can be defined to acquire the tuple.
a = [(0, 1), (2, 3), (4, 5)]
for b, c in a:
print(b, c)
Execution result
0 1 2 3 4 5
You can use the reversed ()
method to sort in reverse order and loop as usual.
d = [0, 1, 2, 3, 4]
for i in reversed(d):
print(i)
Execution result
4 3 2 1 0
By using the ʻenumerate ()` method, you can get the index of the data and the iterator of the tuple consisting of the data specified by the index.
e = ['apple', 'orange', 'melon', 'lemon']
for i, j in enumerate(e):
print(i, j)
Execution result
0 apple 1 orange 2 melon 3 lemon
The zip ()
method returns an iterator consisting of tuples of values at the same index from multiple arguments.
e = ['apple', 'orange', 'melon', 'lemon']
f = ['label1', 'label2', 'label3', 'label4']
for i, j in zip(f, e):
print(i, j)
Execution result
label1 apple label2 orange label3 melon label4 lemon
Recommended Posts