36

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.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
FigNeutron
  • 411
  • 1
  • 4
  • 5
  • 1
    If you need to check if a specific integer is in a `list` a lot, you are better of converting your `list` to a `set`, and check if the integer is in the `set`. – Akavall Jan 30 '13 at 16:09

4 Answers4

57

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")
8

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'
That1Guy
  • 7,075
  • 4
  • 47
  • 59
-2

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' ) 
  • 3
    This answer is wrong. The first stanza produces: Test 1 False, Test 2 False, as one would expect intuitively from python. You should remove this answer, it makes no sense. – datashaman Dec 06 '19 at 05:18
  • 16 in [216] produces False; that is, @datashaman is correct; an int is not a string. – R. Cox Aug 21 '20 at 15:58
-2

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.

GURU Shreyansh
  • 881
  • 1
  • 7
  • 19
Hamza Tanveer
  • 323
  • 1
  • 3
  • 7