Robert Ramonet Robert Ramonet - 2 years ago 57
Python Question

for loop find in list with if statement

I have the following question:

considering the given list :

list = ['12','8','3']

why does
print('8' in list)
returns True


for i in range(5):
if '8' in list == True:

doesn't execute my code inside the if loop ?
Could someone explain me why, and how could I make this work ?

Maybe this question has already been asked but I don't see with which keywords I should search for it.
Thanks for the help :-)

Answer Source

You seem to have some logical errors in your code, so I'll try to outline what you should be doing.

  • You shouldn't name variables str or list or int because they might conflict with Python's built in keywords.

  • Your check did if '8' in list, but that will test if the string 8 is in the list, not the number. Drop the apostrophes.

  • You don't have to put if 8 in list in a loop, it'll do the looping and testing for you.


To check if a number is in a list, you can use python's built in in keyword, your write your own code to do the checking.

Remember not to use keywords like list, so I've changed the name to myList in these examples.

Using in

if 8 in myList:   # Note that you don't have to say == True
    print('8 is in the list!')

Or using for i in myList)

for i in myList:
    if i == 8:
        print('8 is in the list!')**

Or using for i in range(len(myList))

for i in range(len(myList)):
    if myList[i] == 8:
        print('8 is in the list!')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download