Reputation: 4636
a = [1,2,3,4,5]
b = [6,7,8,9,10]
.
for x in a and b:
print(x)
Output: 6 7 8 9 10
for x in a or b:
print(x)
Output: 1 2 3 4 5
Could someone please explain why this output is produced in these two instances.
Upvotes: 1
Views: 55
Reputation: 5406
Python's and
returns the last truthy (evaluates to True
) operand if all are truthy otherwise it returns the first falsey (evaluates to False
) operand.
Lists (with length > 0) are truthy regardless of the values in the list so the one to be iterated over depends solely on the oder:
>>> range(1,5) and range(6,10)
[6, 7, 8, 9]
>>> range(6,10) and range(1,5)
[1, 2, 3, 4]
Python's or
returns the first truthy operand or the last operand if both are falsey. Again lists (with length > 0) are truthy so it's all about ordering here:
>>> range(1,5) or range(6,10)
[1, 2, 3, 4]
>>> range(6,10) or range(1,5)
[6, 7, 8, 9]
Upvotes: 0
Reputation: 121975
In Python, a and b
evaluates the truthiness of the operands a
and b
and returns either the first operand that evaluates False
or, if both operands evaluate True
, the second operand:
>>> [1, 2, 3] and []
[]
>>> [] and [1, 2, 3]
[]
>>> [] and ""
[]
>>> [1, 2, 3] and [4, 5, 6]
[4, 5, 6]
a or b
returns the first operand that evaluates True
or, if both operands evaluate False
, the second operand:
>>> [1, 2, 3] or []
[1, 2, 3]
>>> [] or [1, 2, 3]
[1, 2, 3]
>>> [] or ""
''
>>> [1, 2, 3] or [4, 5, 6]
[1, 2, 3]
They are both lazy, giving up as soon as it can be determined for sure what the outcome will be. Note that empty containers []
and ""
evaluate False
, whereas non-empy containers like [1, 2, 3]
evaluate True
.
Upvotes: 3
Reputation: 12092
The or
operator returns as soon as it finds the first True
value.
>>> x = 1 or 2
>>> x
1
The and
operator evaluates all the operands (in this case two operands) and returns only if all of them are True
>>> x = 1 and 6
>>> x
6
The for loop at each step assigns the comparison result to x
. Hence in the first loop it gets the values of first list and in the second loop gets the values of second list as explained above.
Upvotes: 0
Reputation: 165202
Simple:
>>> a and b
[6, 7, 8, 9, 10]
>>> a or b
[1, 2, 3, 4, 5]
the and
operator will return b
since it has to check both a
and b
. The or
operator sees a
as a value which isn't False
thus immediately returning it.
Upvotes: 6
Reputation: 500177
>>> a or b
[1, 2, 3, 4, 5]
By definition, a or b
evaluates the truthiness of a
and, if a
is true, returns it (otherwise it returns b
).
Upvotes: 0