[Introduction to Python] How to use the in operator in a for statement?

Reference site: [Introduction to Python] How to use the in operator in a for statement?

[Introduction to Python] How to use the in operator in a for statement?

Python has various syntaxes and operators that make coding shorter and easier than in other languages. This time, I will explain in, which is used in various places among many Python operators.

The in operator is an operator to check if an element with a specific value exists in a list or tuple. The basic syntax of the in operator is as follows.

Specified element in list

The part of the list is the same for tuples and dictionaries. The in operator checks if the specified element is present in a list or tuple, and returns True if it is present, False if it is not.

list1 = ['tanaka', 'satou', 'suzuki', 'kimura']

print('tanaka' in list1)
print('takenaka' in list1)

Execution result

True False

In this example, we are checking if there is a person with the specified name in the list of names. Since "tanaka" is in the list, True is returned, and "takenaka" is not in the list, so False is returned.

The in operator can also be used for tuples and dictionaries.

tuple1 = ('tanaka', 'satou', 'suzuki', 'kimura')
dict1  = {'tanaka':21, 'satou':45, 'suzuki':19, 'kimura':67}

print('tanaka' in tuple1)
print('takenaka' in tuple1)

print('suzuki' in dict1)
print('suzumura' in dict1)

Execution result

True False True False

Even if it is a tuple or dictionary type, it can be used in the same way as a list. However, in the case of dictionary type, it is a confirmation whether the specified key exists. Note that even if the specified element is in the value, False is returned if it is not in the key.

dict2  = {'tanaka':'tarou', 'suzuki':'zirou'}

print('tarou' in dict2)

Execution result

False

in operator in for statement

In Python, the for statement also uses the in operator. In in the for statement works to extract elements one by one from lists and tuples.

list1  = ['tanaka', 'satou', 'suzuki', 'kimura']

for name in list1:
    print(name)

Execution result

tanaka satou suzuki kimura

In this example, the elements are extracted one by one from the list. Similar results are obtained with tuples. However, in the case of a dictionary, the key is usually retrieved.

dict1  = {'tanaka':21, 'satou':45, 'suzuki':19, 'kimura':67}

for name in dict1:
    print('{0}:{1}'.format(name, dict1[name]))  #Display the value using the extracted key

Execution result

tanaka:21 suzuki:19 satou:45 kimura:67

Use dictionary values () and items () to retrieve dictionary values or both keys and values in a for statement.

dict1  = {'tanaka':21, 'satou':45, 'suzuki':19, 'kimura':67}

#Extract only the value
for age in dict1.values():
    print(age)
    
#Retrieving keys and values
for item in dict1.items():
    print(item)

Execution result

19 45 21 67 (‘suzuki’, 19) (‘satou’, 45) (‘tanaka’, 21) (‘kimura’, 67)

not in operator

There is a not in operator, which is very similar to the in operator. The in operator returned True if the element you were looking for was in a list or tuple, or False if it wasn't. The not in operator, as the name implies, returns True if it doesn't exist and False if it exists.

list1  = ['tanaka', 'satou', 'suzuki', 'kimura']

print('tanaka' not in list1)
print('takenaka' not in list1)

Execution result

False True

Listing 1 has the name "tanaka", so the not in operator returns False, and there is no name "takenaka", so the not in operator returns True. Both in and not in behave similarly, but use the in operator to confirm "exist" and the not in operator to confirm "non-existence".

Get the index of the element specified by index

By using the in operator, I was able to check if the element exists in a list or tuple. However, even if it is known, it does not know where it is in the list. In such a case, use the index function. The basic syntax of the index function is as follows.

list.index(The element you want to find)

You can use the index function to find out the position of the element you are looking for in the list. If the element is not found in the index function, a ValueError will occur, so it is safe to use the index function after confirming that it exists using the in operator.

list1 = ['tanaka', 'satou', 'suzuki', 'kimura']

name_index = 0
name = 'suzuki'

if(name in list1):
    name_index = list1.index(name)
    print('{0}Is{1}Second exists'.format(name, name_index))

Execution result

suzuki exists second

In this example, the index of the specified element (name) is fetched only when it exists. This will prevent the index function from raising a ValueError.

Of course, you can use the index function alone after handling exceptions, but this is easier than handling exceptions.

Recommended Posts

[Introduction to Python] How to use the in operator in a for statement?
[Introduction to Python] How to use class in Python?
How to use the __call__ method in a Python class
How to define multiple variables in a python for statement
I didn't know how to use the [python] for statement
[Introduction to Python] How to get the index of data with a for statement
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
How to use the C library in Python
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[For beginners] How to use say command in python!
Convenient to use matplotlib subplots in a for statement
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
How to use the model learned in Lobe in Python
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
How to use Mysql in python
How to use ChemSpider in Python
How to use PubChem in Python
[python] How to use the library Matplotlib for drawing graphs
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to generate a query using the IN operator in Django
How to get the last (last) value in a list in Python
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
How to get a stacktrace in python
[Python] Organizing how to use for statements
How to use __slots__ in Python class
How to use "deque" for Python data
How to use regular expressions in Python
How to use is and == in Python
How to determine the existence of a selenium element in Python
[Introduction to Python] How to split a character string with the split function
How to check the memory size of a variable in Python
How to use the asterisk (*) in Python. Maybe this is all? ..
How to check the memory size of a dictionary in Python
[For beginners] How to register a library created in Python in PyPI
How to use MkDocs for the first time
How to clear tuples in a list (Python)
[Introduction to Udemy Python3 + Application] 23. How to use tuples
How to embed a variable in a python string
How to use Python Image Library in python3 series
How to create a JSON file in Python
Summary of how to use MNIST in Python
How to write a ShellScript Bash for statement
[Introduction to Udemy Python3 + Application] 43. for else statement
[Algorithm x Python] How to use the list
How to notify a Discord channel in Python
How to get the files in the [Python] folder
Don't use readlines () in your Python for statement!
How to use tkinter with python in pyenv
[Python] How to draw a histogram in Matplotlib
[Python] Explains how to use the range function with a concrete example
[Introduction to Python] How to write a character string with the format function
How to sort by specifying a column in the Python Numpy array.
How to pass the execution result of a shell command in a list in Python
How to retrieve the nth largest value in Python
[BigQuery] How to use BigQuery API for Python -Table creation-
How to convert / restore a string with [] in python
[Introduction to Python] How to use while statements (repetitive processing)
How to get the variable name itself in python
Use something other than a <br> string for the <br> dict key in Python
How to get the number of digits in Python