0

I have two lists and I want to use both in if condition together.

In case only One list this can do easily
like if list_name : # if list a :
for more than 2 lists this method is not working.

although we can use separately if or using len(a) like comparison.
I am searching for simple & beautiful result.

a = [1,2,34]
b= [4,5,6,3]

# if a & b : # i was expecting this will work <br>
#if (a is True) & (b == True): # this all not working <br>
# if (len(a) >=1) & (len(b) >=1): # This will work but not beautiful <br>
#
    print("Not Working") # 

print("working ")
krishna
  • 1
  • 3

3 Answers3

0

In Python, instead of using & in if statements, we use and.

This is how you can check both lists in the same if:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

if a and b:
    print("a and b are both valid!")

You can read more about Python if statements here.

Brhaka
  • 1,622
  • 3
  • 11
  • 31
0

Inside if-statements, lists are automatically evaluated as True or False, depending on whether they are empty or not. Therefore, we can simply write:

a = [1,2,34]
b = [4,5,6,3]
if a and b:
    print('Hello World')

If you want to check if any list is non-empty, you can write a or b alternatively.


More information about the evaluation of if-statements:

What is Truthy and Falsy? How is it different from True and False?

C-3PO
  • 1,181
  • 9
  • 17
0

Python has a very fancy way, working with lists.

Here are some very basic ones:

a = [1, 2, 3, 4]
b = [4, 5, 6, 7]

if a and b:
    # Checks if there is something inside both lists
    # returns True if there is at least 1 value inside every list
    print("A and B not empty")

if a or b:
    # Checks if there is something at least in one list
    # returns True if there is at least 1 value inside of one list
    print("Something in A or B")
    
if a[0] == b[0]:
    # Checks the first value of both lists
    print("Value 1 of A and B are equal")

# Loops through the list of a / you can use i as index    
for i in range(len(a)):
    if a[i] == b[i]:
        print(f"{a[i]} is equal to {b[i]}")

# Alternative loop
for item in a:
    print(item)
LiiVion
  • 312
  • 1
  • 10