0

Is there any difference in the code given below?

arr = ['a', 'ab', 'abc', 'b', '1', 'c']
if 'a' and 'b' and 'c' in arr:
    print(True)

# VERSUS

arr1 = ['a', 'ab', 'abc', 'b', '1', 'c']
if 'a' in arr1 and 'b' in arr1 and 'c' in arr1:
    print(True)

  • `if "a" and ... in arr` doesn't check `if "a" in arr`, the first statement is equivalent to `if ("a") and ("b") and ("c" in arr):`. Non-empty strings evaluate as truthy and so that first one is just `if "c" in arr:`. You could have `arr = ["c"]` and that first version would still `print(True)`. – Shorn Feb 23 '23 at 05:32

1 Answers1

1

In the first code,

arr = ['a', 'ab', 'abc', 'b', '1', 'c'] 
if 'a' and 'b' and 'c' in arr:
    print(True)

the if 'a' and 'b' and 'c' in an arr statement is not checking if all three strings are in the list.

Instead, it's checking if the string 'a' is true, then checking if the string 'b' is true, and then checking if the string 'c' is in the list.

So it is checking step by step and stop checking when condition is false.

While in your second code

arr1 = ['a', 'ab', 'abc', 'b', '1', 'c']
if 'a' in arr1 and 'b' in arr1 and 'c' in arr1:
    print(True)

if 'a' in arr1 and 'b' in arr1 and 'c' in arr1, correctly checks if all three strings are present in the list arr1.

NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
  • 2
    If you have a lot of variables to check, you can also do use `all`. `check = ["a", "b", "c"]`, `if all(value in arr for value in check)` – Shorn Feb 23 '23 at 05:37