Python #loop

loop

Get tuples in a loop

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

Loop in reverse order

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

Loop while getting index

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

Loop through multiple lists at the same time

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

Python #loop
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Python comprehension
Python technique
Studying python
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Paiza Python Primer 3: Learn Loop Processing
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
python memo
Python memorandum
Python # sort
ufo-> python
Python nslookup
python learning
Hannari Python 2020
[Rpmbuild] Python 3.7.3.
Prorate Python (1)
python memorandum
Download python
python memorandum
Python memo