6

I have a list of list that contains all the conditions that the if statement has to satisfy, but the problem is that the number of conditions stored into the list of list is unknown. For e.g., the list of list is like this:

my_list: [["A", "0"], ["B", "1"], ["C", "2"]]

so the if should be:

if A==0 and B==1 and C==2:
      #do-something
else:
      pass

since I don't know the number of elements in the list of lists, I cannot do:

if my_list[0][0]==my_list[0][1] and my_list[1][0]==my_list[1][1] and my_list[2][0]==my_list[2][1]:
     #do-something
else:
      pass

how do I solve this problem?

A similar problem has been raised here but there is no a clear explanation/implementation of this problem.

Thanks.

2 Answers 2

7

You can use a generator expression within all():

if all(i == j for i, j in my_list): # use int(j) if 'j' is string and 'i' is integer.
    # do something
Sign up to request clarification or add additional context in comments.

Comments

2

I think @Kasramwd provides the most pythonic solution, but an alternative makes use of Python's else clause on a for loop.

for item in my_list:
    if item[0] != item[1]:
        break
else:
    # do-something

Comments

Your Answer

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.