madsthaks
madsthaks

Reputation: 2181

Attempting to check if a list isn't empty AND some other condition within the same if statement

The easiest way to explain this is to show a simple example:

x = [0]

f = 4
if (x) & (f < 6):
    print("yes")

The idea is simple, check if a list contains any content and if some other variable is less than some number.

The solution yields the following error and I'm not entirely sure what the solution is.

TypeError: unsupported operand type(s) for &: 'list' and 'bool'

Upvotes: 2

Views: 39

Answers (2)

Maxime Ch&#233;ramy
Maxime Ch&#233;ramy

Reputation: 18821

& is the "bitwise and" operator, while and is the logical and operator.

The correct if statement is the following:

if x and f < 6:
    print("yes")

Note that the parentheses aren't necessary here. Also, in Python a non-empty list is evaluated as True, that's why you can use x instead of len(x) > 0 which is also correct.

Upvotes: 3

Mureinik
Mureinik

Reputation: 311163

& isn't the logical "and" operator in Python, it's the bitwise and operator. Instead, you should use the logical "and" operator, which is simply and:

if (x) and (f < 6):
    print("yes")

Upvotes: 3

Related Questions