Python iterative

I summarized the iterative processing of python. For beginners. python version: 3.6.9 The following is a reference for the official document. for statement / while statement range

Use Range for

Iterations that use Range objects are mainly used for loop processing that specifies the number of times. The Range object can be created by setting range (start, stop, step), and by using it in the for statement, it is possible to execute while increasing from start to stop -1 (stop itself is not included) step by step. I can do it. Here are some examples.

Repeat N times

for i in range(5):
  print(i)
# 0 ~4 is output
#The Range initializer has a default value of 0 for start and 1 for step.

Start from 1 and repeat while increasing by 2

#You can loop in any order by changing the value given to step.
for i in range(1, 10, 2):
  print(i)
#1, 3, 5, 7,9 is output

Repeat while reducing the value

On the contrary, it is possible to execute while reducing.

#start is 10, stop is-1, step is-Since it is 1, it processes from 10 to 0 while decreasing by 1.
for i in range(10, -1, -1):
  print(i)
#10 ~Output while decreasing 0

For Here's how to use for when you don't use range. It is mainly used for collective operations such as iterables.

Iterate over all elements such as lists

It corresponds to foreach in Java. You can process objects called iterables. Lists, sets, tuples, etc. (The one that implements __iter__ () is called iterable, but detailed explanation is omitted.)

#Repeat all elements of the list
a = [1, 3, 5, 7]
for n in a:
    print(n)

#Same for the set
s = {1, 2, 3, 4}
for n in s:
    print(n)

For the dictionary, the key and value are retrieved using the method of the dictionary.

#Handle all keys
for k in m.keys():
  print(k)

#Handle all values
for v in m.values():
  print(v)

#Process for key / value pairs
for k, v in m.items():
  print(str(k) + v)

Repeat with index

Use ʻenumerate` if you want to scan elements while also using indexes.


a = ['a', 'b', 'c', 'd', 'f']
for i, n in enumerate(a):
    print(i, n)
#The output is as follows.
#0 a
#1 b
#2 c
#3 d
#4 f

Process multiple iterables at the same time

Use zip () if you want to handle multiple iterable elements in sequence at the same time.

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd', 'e']

for i, j in zip(a, b):
    print(str(i) + j)

Note that if the iterables have different numbers of elements, the extra (higher number of elements) elements will be ignored.

#Of the elements in list a, the last three are not processed
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = ['a', 'b', 'c', 'd', 'e']

for i, j in zip(a, b):
  print(str(i) + ' ' + j)

#1 a
#2 b
#3 c
#4 d
#5 e

# 6 ~8 is not output!

While while continues to execute processing "while satisfying certain conditions".

#In this example, processing continues while i is less than 10.
i = 0
while i < 10:
  print(i)
  i += 1
# 0 ~9 is output.

The code below is an infinite loop because it keeps running as long as the conditions are met.

#A simple example of an infinite loop
#Infinite loop because the while condition is always True
while True:
  print('hoge')

continue, break, else continue, break, ʻelsedoes not realize loop processing by itself, but by combining withfor and while` mentioned above, processing is interrupted or skipped during loop processing, etc. You will be able to.

continue continue skips the following processing and moves on to the next loop processing. It is used when you do not want to process under specific conditions.

for i in range(10):
  if i % 2 == 0:
    #If it is an even number, continue is executed and the next loop processing is performed.
    continue
  print(i)
# 1,3,5,7,9 is output

break break terminates the loop process itself. It is used when you want to end the loop processing when a specific condition is met.

for i in range(10):
  #Since the process ends when i is 7, the numbers after 7 are not output.
  if i == 7:
    break
  print(i)
#0,1,2,3,4,5,6 is output

else ʻElse` is a block that is executed after the loop processing is finished and when the loop is not finished by break.

for i in range(10):
  print(i)
else:
  print('done!')
#0 ~After 9 is output, done!Is output.

If you break out of the loop with break, else will not be executed, so in the example below, the else clause will not be executed.

for i in range(10):
  if i == 7:
    break
  print(i)
else:
  print('done!')

# 0 ~6 is output and processing ends

As mentioned above, I will edit it again when I have more knowledge about loop processing.

Recommended Posts

Python iterative
Python
[Python] Iterative processing_Personal memorandum
[Python] Iterative processing (for, while)
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
ufo-> python (3)
Python comprehension
install python
Python Singleton
python memo
Python Jinja2
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
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