Home > Mobile >  python execute if statement if value matches any elements of a list
python execute if statement if value matches any elements of a list

Time:09-08

I want to print elements of a list under a for loop one by one using an if statement. here's what I did:

   list[4,15,17,18,19,23,30,31,32,33,38,39,48,49,52,54,55,56,66]
   for i in range(0,67):
        if i==any(list):
            print(i)

I only want the if statement to run if i equals to any one of the values inside the list which is [4,5,6,17,18,19,23,30,31,32,33,38,39,48,49,52,54,55,56,66]

one can do it by writing multiple if statement like:

if i==4:
    print(i)
if i==15:
    print(i)
if i==17:
    print(i)
.......
if i==66:
    print(i)

Please let me how to do that. Thanks.

CodePudding user response:

You can check if it is in range, for example:

alist = [4, 15, 17, 18, 19, 23, 30, 31, 32, 33, 38, 39, 48, 49, 52, 54, 55, 56, 66]

r = range(0, 67)

for i in alist:
    if i in r:
        print(i)

Through I'm not sure why you need this, can you share some details?

CodePudding user response:

Try running the below code.

temp_list = [4,15,17,18,19,23,30,31,32,33,38,39,48,49,52,54,55,56,66]
for i in range(0,67):
    if i in temp_list:
        print(i)
  • Related