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.
4 Answers 4
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")
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'
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' )
-
5This 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– datashaman12/06/2019 05:18:56Commented Dec 6, 2019 at 5:18
-
16 in [216] produces False; that is, @datashaman is correct; an int is not a string.R. Cox– R. Cox08/21/2020 15:58:27Commented Aug 21, 2020 at 15:58
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.
-
if isinstance(x , int): print(x) Should be? if isinstance(i , int): print(i)Bruce Bookman– Bruce Bookman12/15/2021 16:46:47Commented Dec 15, 2021 at 16:46
Explore related questions
See similar questions with these tags.
list
a lot, you are better of converting yourlist
to aset
, and check if the integer is in theset
.