Hello to all! Then a question came to the mail: checking for an element in a list in Python – how to implement this?
Simple 🙂 Sample code is below:
A simplified diagram is as follows:
1. There is a list of mass
2. The variable X is entered by the user, and has a string type (we don’t know what is specific and what type is in the list, right?
3. Connect the loop, and iterate over it. If the iterable value is equal to the value of the variable x, we will receive the message “Ok!”, Otherwise, we will display the message “No!”
In code form, it looks like this:
mass = [’11’, ’12’, ’13’, ’14’, ’15’] # create a list consisting of six elements
x = str (input (‘Enter X:’)) # create a string variable x
for i in mass: # start a cycle that will work on the mass list
if i == x: # check the list item
print (‘Ok!’) # if the list item to be checked is equal to the value of the variable = display a message
break # we finish work with a cycle
else: # start the branch that is responsible for the action if the item is not found
print (‘No!’) # We print a negative message if the desired element x is not found in the list
break # we finish work with a cycle
UPD: thanks to reader Ilya, who pointed out an error in the code. The version below is smaller and works with the entire list 😉
-
mass = ['11', '12', '13', '14', '15']
-
x = str(input('Input x: '))
-
for i in mass:
-
if i == x:
-
print('ok!')
An example of checking the presence of an item in the list on the video:
And yes, the lists are described in more detail here here 🙂
Thanks for attention!