Reference site: [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 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)
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".
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