Just thought I’d share a bunch of neat (and weird) things I’ve noticed about the Python programming language:
- You can chain comparisons as in
assert 3.14 < pi < 3.15. It’s a neat equivalent of
assert pi > 3.14 and pi < 3.15that you can’t do in most other languages.
Ints don’t overflow at 31 (or 32) bits, they just get promoted to longs automatically. And long in Python doesn’t mean 64 bits, it means arbitrarily long (albeit somewhat slower). In fact, it looks like in Python 3000 there won’t even be the int/long distinction.
Default values are only evaluated once, at compile-time, not run-time. Try
def func(A=): A.append(42); return Aand the A-list will grow between calls. The Python tutorial has more.
When concatenating strings,
''.join(list)is much faster than
for x in list: s += x. In fact, the
joinis O(N) whereas the
+=is O(N²). There’s been a lot of debate about making this faster, and it looks like it should be faster in Python 2.5, but my tests show otherwise. Any ideas why?
The syntax of
print >>file, valuesis just plain weird. Not to mention the spacing “features” of
You can create a one-element tuple with
(x,). Tuples are normally written
(x, y, z), but if you go
(x)Python sees it as just a parenthesised value.
And for all those times you reference methods of integer literals, you can go
(5).__str__. You’d think it’d be just
5.__str__, but the parser thinks the
5.is a float and then gets stuck.
else:clause after a
forloop will be executed only if the loop doesn’t end via
break. Quite useful for search loops and the like — in other languages you often need an extra test after the loop.
You tell me yours. Ha! You thought you were going to escape. :-)
16 January 2008 by Ben 40 comments