Home > Enterprise >  Python: If any variable in list exists, then print the item
Python: If any variable in list exists, then print the item

Time:11-25

I have a list of 0s, named "variables". One of the 0s will become -1 spontaneously, and I'm trying to print the element which does. For example, this is my code:

while True:
    if any(variables):
        print(variables[i])

Now, obviously "i" doesn't correlate to anything, but I'd like it to represent the index of the non-zero variable in the list "variables". Should I enumerate? Is there an easy way to do this with list comprehension? Thank you!

CodePudding user response:

Try

print(list(filter(lambda x: x==-1, variables)))

CodePudding user response:

Do you want to get the index? Outputting the element would be equal to just writing print(-1)

print variables.index(-1)
  • Related