2

I am wondering about why [] and {} return [] in python?

>>> [] and {}
[]

Edit: Why are [] and {} false?I understand and or expressions , but i cannot understand [] and {} expressions are false?

my-lord
  • 2,453
  • 3
  • 12
  • 26
  • Because they both are `False` then first is returned. – vishes_shell Feb 25 '18 at 20:43
  • Why [] and {} false?I understand and or expressions , but i cannot understand [] and {} expressions are false? – my-lord Feb 25 '18 at 21:02
  • 1
    @mw-b, ...because they're empty. See ie. [empty list boolean value](https://stackoverflow.com/questions/12997305/empty-list-boolean-value), or [How do I check if a list is empty?](https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty). – Charles Duffy Feb 25 '18 at 21:09

1 Answers1

3

In the short circuit evaluation containing only operator and (could be multiple) and multiple operators, the expression returns the first falsy value, in this case which is [] -- an empty list.

In the case where all the values are truthy, it returns the last value.

# [] and {} both are falsey
In [77]: [] and {}
Out[77]: []

# 3 is truthy, {} is falsey
In [78]: 3 and {}
Out[78]: {}

# all except {} are truthy
In [79]: 3 and 9 and {}
Out[79]: {}

# you get it...
In [80]: 3 and 9 and {} and 10
Out[80]: {}
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • In addition to this, the reason that the _first_ falsy value is returned rather than some other one like the last or middle is that of an optimization technique called [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation). – Ziyad Edher Feb 25 '18 at 20:45
  • or the second value if neither are falsey – avigil Feb 25 '18 at 20:45
  • @avigil Just added. – heemayl Feb 25 '18 at 20:45