How to check if there is an element in a Python list?

Asked

Viewed 3,640 times

2

I’m trying to do an algorithm in Python to check if there’s an element in a certain list. If yes, the program will print on the screen, if not, it will add a new element in the list.

My intention is to create a list with 4 elements and add 6 more. I will print the elements contained in it and if you do not find more elements (from the 4th loop), add what I want.

I made the code like this:

nomes = ['A', 'B','C','D','E']
i=0
for x in range(10):
    if : #precisoSaberQualCondiçãoColocarAqui
         print(x)
    else:
        nomes.append(i)
        i+=1
print(nomes)
  • 1 in [1,2,3] # True. Use command in. He checks if there’s anything on the list.

1 answer

3


You can use the command in:

1 in [1,2,3] # True
7 in [1,2,3] # False

In the case of if:

if x in nomes:
   print(x)
  • Solved right!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.