Weird things in Python

Short Circuit

  • a and b evaluates to a if a is falsey, otherwise it evaluates to b
  • a or b evaluates to a if a is truthy, otherwise it evaluates to b
  • not a evaluates to True if a is falsey, otherwise it evaluates to False
1
2
3
4
5
>>> 0 and 'Hello' 0
>>> 'x' and 'y' 'y'
>>> '' or 0
0
>>> -23 or False -23
  • True is represented as 1, and False is represented as 0.
1
2
3
4
5
6
>>> True == 1 
True
>>> False == 0
True
>>> False == ''
False # because False == 0, but 0 != '', because '' == ord('')

Different Behavior in shell/script

1
2
3
4
5
6
7
8
>>> n1, n2 = 1234e23, 1234e23
>>> id(n1), id(n2)
(4317529008, 4317529008)

>>> n1 = 1234e23
>>> n2 = 1234e23
>>> id(n1), id(n2)
(4318748880, 4318749104)

The one line if:

  1. don't have an else: if True: print('xxx')

  2. have an else and assign the value: x = 1 if True else 0

    can't say else x = 1.

  3. have an else and don't wanna assign: dirty hack: ignore the returning value:

    x = 1 if False else print(0), the print will return None to x.

    print(1) if True else print(0), normally do.

ls[:] = [1, 2, 3] To change a list in a function

1
2
3
4
5
6
def changeLS(ls):
ls[:] = [1, 2, 3]
ls = [4,5,6]
changeLS(ls)
print(ls)
# ls = [1,2,3] then.