A little girl goes into a pet show and asks for a wabbit. The shop keeper looks down at her, smiles and says:
"Would you like a lovely fluffy little white rabbit, or a cutesy wootesly little brown rabbit?"
"Actually", says the little girl, "I don't think my python would notice."
—Nick Leaton, Wed, 04 Dec 1996
generators
>>> x = (7, 8, 9)
>>> sorted(x) == x
False
>>> sorted(x) == sorted(x)
True
>>> y = reversed(x)
>>> sorted(y) == sorted(y)
False
references
>>> a = [[0]] * 5
>>> print(a)
[[0], [0], [0], [0], [0]]
>>> a[0] += [1]
>>> print(a)
[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]
assignment
>>> a = {}
>>> for a['b'] in [1, 2, 3]:
... pass
...
>>> a
{'b': 3}
closures
>>> powers_of_x = [lambda x: x^i for i in range(10)]
>>> [f(2) for f in powers_of_x]
[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]
inheritance
>>> isinstance(type, object)
True
>>> isinstance(object, type)
True
operator chaining
>>> False == False in [False]
True
>>> False == (False in [False])
False
>>> (False == False) in [False]
False
>>> (False == False) and (False in [False])
True
identity
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a = 257; b = 257
>>> a is b
True
nfkc normalization
>>> 𝕡𝕣𝕚𝕟𝕥(𝕖𝕧𝕒𝕝('1+1'))
2
>>> 𝕖𝕧𝕒𝕝(𝕚𝕟𝕡𝕦𝕥())
print('1')
1
default arguments
>>> def foo(x, a=[]):
... a.append(x)
... print(a)
>>> foo(1)
[1]
>>> foo(2)
[1, 2]
>>> a = 1
>>> def foo(x=a):
... print(x)
>>> a = 2
>>> foo()
1
whatever this is
>>> [0x1for _ in (0, 1, 2)]
[31]
python 2
f = open('file.txt','w')
print >> f, 'Hello world'
>>> input()
__import__('os').system('bash')
$ whoami
root
>>> True, False = False, True
>>> print True
False
exponentiation
>>> 2^3
1
split
>>> ''.split(' ') == ''.split()
False
>>> 'a'.split(' ') == 'a'.split()
True
>>> len(' '.split(' ')) == len(' '.split())
False
>>> len(' '.split(' ')) == len(' '.split())
True
uncommon syntax
>>> for a in b:
... # dostuff
else:
... # executed at the end of the loop, unless break is called
>>> print(*['a', 'b', 'c'])
a b c
>>> print(...)
Ellipsis
>>> a = [1,2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>> a[2]
[1, 2, [...]]
>>> a[2][2][2][2][2][2][2][2][2] == a
True
a, b = 1, 2
a, b = b, a
further reading
https://github.com/satwikkansal/wtfpython
https://www.reddit.com/r/Python/comments/4oje6w/whats_your_favorite_python_quirk/
https://www.reddit.com/r/Python/comments/84l0p0/what_are_some_python_quirks_that_youve_found/
https://blog.pepsipu.com/posts/albatross-redpwnctf
Some of these are hilarious. Thanks for sharing.
I think some deserve a little more depth. I wrote this. https://slott56.github.io/2023-08-01-python_quirks_that_arent_very_quirky.html
There is a large collection of Python oddities here:
https://wtfpython-interactive.vercel.app/