+ 2
Is there a way to check if there is a range of numbers in a list?
If I have a list, a =[5,10,15,20] Is there a way to check if any number between 1-5 is in the list, without having to write 5 if statements?
4 Antworten
+ 8
any([i in a for i in range(1,6)])
+ 4
Sanjyot21 That's a first for me.
Are you sure your code works this way?
I've attempted with no success.
Here's my test code:
----
a = [5, 10, 15, 20]
b = [1,2,3,4,5]
c = [4,5]
if a in b:
print("Matched using a in b")
if b in a:
print("Matched using b in a")
if c in b:
print("Matched using c in b")
if b in c:
print("Matched using b in c")
if range(1,6) in a:
print("Matched using range(1,6) in a")
if any([i in a for i in range(1,6)]): #True
print("Matched using List Comprehensions")
if 5 in a: #True
print("Matched using 5 in a")
+ 4
Sanjyot21
your answer is a good wakeup call!
for a = [1,2,3,range(1,6)] it should work.
So although not correct:
Thanks for contribution.
If understood this, the results of David Carroll s testCases become clear.
+ 1
Use this code......
if range(1,6) in a:
#your code goes here
Hope it helped