[Python] How to use the for statement. A method of extracting by specifying a range or conditions.

[Python] How to use the for statement. A method of extracting by specifying a range or conditions.

Explains how to use for statements, which are often used in python, by pattern.

It's often used in complex combinations and looks difficult, but the basic syntax is very simple, just specify two elements.


**table of contents**
  1. [Basic syntax](# 1 basic syntax)
  2. [Processing details](# 2 Processing details)
  3. [Example](# 3 example)
  4. [Retrieve element of list](Extract element of #list)
  5. [Retrieve the value of the range function](Retrieve the value of the #range function)
  6. [Specify a range and retrieve](#Specify a range to retrieve)
  7. [Specify starting number](# -1 Specify starting number)
  8. [Specify the extraction range](# -2 Specify the extraction range)
  9. [Specify the extraction range and change amount](# -3 Specify the extraction range and change amount)
  10. [Specify the condition with the if statement](# 4 Specify the condition with the if statement)
  11. [Control statements often used with if statements](# 5 Control statements often used with if statements)
  12. [break statement: end processing](#break statement)
  13. [continue statement: skip processing](#continue statement)
  14. [pass statement: do nothing](#pass statement)

## 1. 1. Basic syntax `for a in A:` └ "a": Variable (optional) └ "A": Data └ ":": Installed at the end of the line (otherwise an error will occur)

▼ Supplementary data (“A” above) -Often executed for character strings and numbers. -Often specified by variables. -It also works in the form of directly describing a set of multiple elements such as list and tuple, or a single numerical value or character string.


## 2. Contents of processing

Take one element of A and store it in a variable ("a" in the above). Repeat this ** for the number of elements **.

Every time one element is taken out, ** the process described in the second and subsequent lines is executed **.


3. 3. Illustration

-Retrieve the elements of list (number, character string) ・ Used for tuple type and set type ・ Extract the numerical value with the range function -Specify extraction conditions with an if statement

① Extract the elements of list

Examples of numbers and strings, variable specifications and direct description.

Extracting the numeric elements of a variable


list = [1,2,3]

for a in list:
    print(a)

#output
1
2
3

Extracting a string element of a variable


list = ["AAA","BBB","CCC"]

for a in list:
    print(a)

#output
AAA
BBB
CCC

Specify numerical value directly


for a in [1,2,3]:
    print(a)

#output
1
2
3

Specify character string directly


for a in ["AAA","BBB","CCC"]:
    print(a)

#output
AAA
BBB
CCC

It can also be used for tuple type and set type.

Tuple type


tuple = "AAA","BBB", "CCC"
tuple   #output:('AAA', 'BBB', 'CCC')
type(tuple)   #Output: tuple

for a in tuple:
    print(a)

#output
AAA
BBB
CCC

Set type


set = {1,1,2,2,3,3,3,4}
set   #output:{1, 2, 3, 4}
type(set)   #Output: set

for a in set:
    print(a)

#output
1
2
3
4

Note: Click here for a description of tuples (https://qiita.com/yuta-38/items/e2306af6a378430ec873)


### (2) Extract the numerical value of the range function The handling of data stored in range type in for statement is the same as list type.
** Example 1: `range (5)` ** A numerical value corresponding to the amount of change +1 in the range of 0 to 4. ⇒ [0, 1, 2, 3, 4]

python


for a in range(5):
    print(a)

#output
0
1
2
3
4

** Example 2: `range (0,8,2)` ** A value corresponding to the amount of change +2 in the range of 0 to 7. ⇒ [0, 2, 4, 6]

python


for a in list(range(0,8,2)):
    print(a)

#output
0
2
4
6

** ▼ Supplement: About the range function ** A function that specifies "initial value", "end value of range", and "change amount" and stores the corresponding numerical value in range type.

Click here for details on the range function [https://qiita.com/yuta-38/items/408dba0df6264878a83b)


## ③ Specify the range and take out

It is possible to specify the target range by using slices.

** ▼ What is a slice? ** ** A type of range specification method such as list. Notation to specify the range with [] and :.

** ▼ Slice basic syntax ** [a:b:c] └ "a": Starting sequence number └ "b": Ending sequence number (less than) └ "c": Change syntax

b and c can be omitted

Click here for a detailed explanation of the slices (# https://qiita.com/yuta-38/items/0d5c55b748d10f83af53)


#### ③-1 Specify the starting number

** Example When extracting the third and subsequent elements ** [2:] └ Element counts from 0

Specify the number to start


list = [1,2,3,4,5,6,7,8,9]

for a in list[2:]:
     print(a)

#output
3
4
5
6
7
8
9

#### ③-2 Specify the extraction range

** Example Extract the 5th to 8th elements ** [4:8] └ Element counts from 0 └ Array number 4 is the 5th element └ Array number 8 is the 9th element └ Sequence number 8 is not included (end of processing)

Specify the number to start


list = [1,2,3,4,5,6,7,8,9]

for a in list[4:8]:
     print(a)

#output
5
6
7
8

#### ③-3 Specify the extraction range and the amount of change

** Example Extract the value obtained by adding 3 by 3 from 50 to 70 ** [50:71:3] └ 50th sequence number └ Ends at the 71st sequence number (does not include the 71st value) └ Change amount: Increase by 3

Use range (1,100) └ Integer from 1 to 99

Specify the range to be extracted and the amount of change


for a in range(1,100)[50:71:3]:
    print(a)

#output
51
54
57
60
63
66
69

## 4. Specify the condition with the if statement By using the if statement, it is possible to extract only the values that match the specified conditions.

For the if statement, click here (https://qiita.com/yuta-38/items/f974272a676d8171f4b3)

** ▼ Example of combination of for statement and if statement ① **

Extract only even numbers from the numbers 1-9. (10 not included)

Take out only even numbers


for a in range(1,10):
    if a%2 == 0:
        print(a)

#output
2
4
6
8

└ "%" remainder └ "a% 2 == 0" The remainder of dividing a by 2 is 0 (= even)

** ▼ Example of combination of for statement and if statement ② ** From the numerical values from 1 to 100, the numerical values that are even numbers, 90 or more, and do not include 100 are extracted by list type. (101 not included)

Combination of comparison operators


list = []

for a in range(1,101):
    if a%2 == 0 and a >= 90 and not a == 100:
        list.append(a)

list

#output
# [90, 92, 94, 96, 98]

## 5. Control statements often used with if statements ① break statement: End processing ② continue statement: Skip processing ③ pass statement: do nothing
### ① break statement Terminates processing under the specified conditions.

Basic syntax of break statement (in if statement)


if A:
   break

If condition A, processing is interrupted.


** ▼ Practical example of break statement ** Extract an even number from 1 to 20. If a becomes larger than 10, the process ends.

Practical example of break statement


for a in range(1,20):
    if a%2 == 0:
        if a > 10:
            break
        print(a)

#output
2
4
6
8
10

### ② continue statement The process is skipped under the specified conditions.

Basic syntax of continue statement (in if statement)


if A:
   continue

Condition A skips processing. Others are executed.


** ▼ Practical example of continue statement ** Extract 0 to 4 one by one. However, only 3 is skipped.

Practical example of continue statement


for a in range(0,5):
    if a == 3:
        continue
        
    print(a)

#output
0
1
2
4

** ▼ Practical example of continue statement ② ** Skip even numbers from 0 to 10 and extract. (Extract only odd numbers)

Practical example of continue statement ②


for a in range(0,11):
    if a%2 ==0  :
        continue
        
    print(a)

#output
1
3
5
7
9

### ③ pass statement

The process does not change whether it is described or not. ** Described to clearly indicate that it will not be processed.


** ▼ How to use in if statement ** It is often described to clearly indicate that nothing is specified in the processing of else.

Basic syntax of pass


if A:
    AAA
else:
    pass

If the condition is "A", the process "AAA" is executed. Otherwise, do nothing.

▼ The process is the same as below.

python


if A:
    AAA

#### ■ Confirm that pass does not affect processing It is considered that there are no more than one pass. * Ignoring indentation or writing in a conditional expression will result in a syntax error.

** ▼ (Original processing) Processing to extract even numbers from 1 to 10 **

Original processing


list = []
for a in range(1,11):
    if a%2 == 0:
        list.append(a)
list

#output
[2, 4, 6, 8, 10]

There is a pass ①


list = []
for a in range(1,11):
    if a%2 == 0:
        pass
        list.append(a)
list

#output
[2, 4, 6, 8, 10]

There is a pass ②


list = []
for a in range(1,11):
    if a%2 == 0:
        list.append(a)
        pass
list

#output
[2, 4, 6, 8, 10]

There is a pass ③


list = []
for a in range(1,11):
    pass
    pass
    if a%2 == 0:
        pass
        pass
        pass
        list.append(a)
        pass
list

#output
[2, 4, 6, 8, 10]

** ▼ Error if the conditions for writing syntax are not met **

pass error ①


list = []
for a in range(1,11):
    if a%2 == 0: pass
        list.append(a)
list

#output
# IndentationError: unexpected indent

pass error ②


list = []
for a in range(1,11):
    if a%2 == 0:
        pass pass
        list.append(a)
list

#output
# SyntaxError: invalid syntax

[Return to top](How to extract by specifying the usage range and conditions of the #pythonfor statement)

Recommended Posts

[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
[Introduction to Python] How to use the in operator in a for statement?
[Introduction to Python] How to get the index of data with a for statement
How to use the __call__ method in a Python class
I didn't know how to use the [python] for statement
[Python] Explains how to use the range function with a concrete example
How to sort by specifying a column in the Python Numpy array.
[python] How to sort by the Nth Mth element of a multidimensional array
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
How to execute a schedule by specifying the Python time zone and execution frequency
How to extract conditions (acquire all elements of Group that satisfy the conditions) for Group by Group
[Python] How to make a list of character strings character by character
[python] How to use the library Matplotlib for drawing graphs
How to override a user-defined method generated by python swig
How to calculate space background X-ray radiation (CXB) with python by specifying the flux range
How to determine the existence of a selenium element in Python
[Python] How to force a method of a subclass to do something specific
How to change the log level of Azure SDK for Python
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
How to use machine learning for work? 01_ Understand the purpose of machine learning
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
Put the process to sleep for a certain period of time (seconds) or more in Python
How to intercept or tamper with the SSL communication of the actual iOS device by a proxy
[Python] Summary of how to use pandas
[Python] Organizing how to use for statements
[Python2.7] Summary of how to use unittest
Pandas of the beginner, by the beginner, for the beginner [Python]
How to use "deque" for Python data
[Python2.7] Summary of how to use subprocess
[Question] How to use plot_surface of python
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Python] How to read a csv file (read_csv method of pandas module)
How to format a list of dictionaries (or instances) well in Python
[Introduction to Python] What is the method of repeating with the continue statement?
How to calculate the volatility of a brand
How to use the C library in Python
How to use MkDocs for the first time
[Python] How to use two types of type ()
Sort the elements of the array by specifying the conditions
Summary of how to use MNIST in Python
How to write a ShellScript Bash for statement
[Algorithm x Python] How to use the list
How to erase the characters output by Python
How to pass the execution result of a shell command in a list in Python
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
Python script to get a list of input examples for the AtCoder contest
How to use loc / iloc / ix to get by specifying a column in CASTable
How to get a list of files in the same directory with python
How to save the feature point information of an image in a file and use it for matching
[Python] How to deal with the is instance error "is instance () arg 2 must be a type or tuple of types"
How to use the Slack API using Python to delete messages that have passed a certain period of time for a specific user on a specific channel
Use data class for data storage of Python 3.7 or higher
Create a dataset of images to use for learning
[BigQuery] How to use BigQuery API for Python -Table creation-
[For beginners] How to use say command in python!
How to use pip, a package management system that is indispensable for using Python
[Python] I want to use only index when looping a list with a for statement
A memo of how to use AIST supercomputer ABCI
I tried to summarize how to use matplotlib of python