How to check if a specific integer is in a list

Question:

I want to know how to make an if statement that executes a clause if a certain integer is in a list.

All the other answers I’ve seen ask for a specific condition like prime numbers, duplicates, etc. and I could not glean the solution to my problem from the others.

Asked By: FigNeutron

||

Answers:

Are you looking for this?:

if n in my_list:
    ---do something---

Where n is the number you’re checking. For example:

my_list = [1,2,3,4,5,6,7,8,9,0]
if 1 in my_list:
    print 'True'
Answered By: That1Guy

You could simply use the in keyword. Like this :

if number_you_are_looking_for in list:
    # your code here

For instance :

myList = [1,2,3,4,5]

if 3 in myList:
    print("3 is present")
Answered By: user740316

I think the above answers are wrong because of this situation:

my_list = [22166, 234, 12316]
if 16 in my_list: 
     print( 'Test 1 True' )
 else: 
      print( 'Test 1 False' ) 

my_list = [22166]
if 16 in my_list: 
    print( 'Test 2 True' )
else: 
    print( 'Test 2 False'  )

Would produce:
Test 1 False
Test 2 True

A better way:

if ininstance(my_list, list) and 16 in my_list: 
    print( 'Test 3 True' )
elif not ininstance(my_list, list) and 16 == my_list: 
    print( 'Test 3 True' )
else: 
    print( 'Test 3 False' ) 
Answered By: Justin MacCreery

If you want to see a specific number then you use in keyword but let say if you have

list2 = ['a','b','c','d','e','f',1,2,3,4,5,6,7,8,9,0]

Then what you can do. You simply do this:

list2 = ['a','b','c','d','e','f',1,2,3,4,5,6,7,8,9,0]
for i in list2:
if isinstance(x , int):
    print(x)

this will only print integer which is present in a given list.

Answered By: Hamza Tanveer