0

I have to check for multiple 'and' conditions in if Eg:

if (a[1]==b[1]) and (a[2]==b[2]) and (a[3]==b[3]) and (a[4]==b[4]):

can I do above using for loop in if, say something like

if (a[i]==b[i] for i in range(0,4)):

Above suggested won't work as it sets the condition as true even if one of them is true.

3
  • What are a and b? Commented Nov 23, 2015 at 7:29
  • so you want to check if 2 arrays or lists are the same? Commented Nov 23, 2015 at 7:29
  • Here a and b are dictionaries. for i in range(0,4) could be substituted to for parameter in parameters Commented Nov 23, 2015 at 7:30

2 Answers 2

7

Simply use all() here:

if all(a[i]==b[i] for i in range(1, 5)):

From the document:

Return True if all elements of the iterable are true (or if the iterable is empty).

And (a[i]==b[i] for i in range(1, 5)) return a generator(it's an iterable), then all() return True if all elements in that generator is True, else False. Like your code does.

Sign up to request clarification or add additional context in comments.

1 Comment

@user3798653 if an answer solved your issue, consider accepting it
2

You can do

if all(a[i]==b[i] for i in range(1,5)):
    # logic here

Usage of all():

  1. if all the elements in iterable are True returns True
  2. if one lement is False it return False

eg: all([True,True]) --> True all([False,True])--> False

1 Comment

@MartijnPieters Ahh,Sorry Forgot

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.