38

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
143k34 gold badges253 silver badges286 bronze badges
asked Jan 30, 2013 at 15:47
1
  • 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. Commented Jan 30, 2013 at 16:09

4 Answers 4

62

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 Jan 30, 2013 at 15:49
0
9

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 Jan 30, 2013 at 15:48
-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' ) 
answered Nov 13, 2019 at 19:57
2
  • 5
    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. Commented Dec 6, 2019 at 5:18
  • 16 in [216] produces False; that is, @datashaman is correct; an int is not a string. Commented Aug 21, 2020 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
9091 gold badge8 silver badges19 bronze badges
answered Nov 29, 2020 at 15:10
1
  • if isinstance(x , int): print(x) Should be? if isinstance(i , int): print(i) Commented Dec 15, 2021 at 16:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.