> reversed(sorted(my_list))
I thought sorted(my_list, reverse=True) would be slightly faster, but it seems not (by a tiny amount). Weird.
> "while True" should be used in-place of "while 1". Reads better.
If you disassemble these statements, you'll see that "while 1" creates fewer instructions:
def foo():
while True:
pass
def bar():
while 1:
pass
import dis
dis.dis(foo)
# 0 SETUP_LOOP 10 (to 13)
# >> 3 LOAD_GLOBAL 0 (True)
# 6 POP_JUMP_IF_FALSE 12
#
# 9 JUMP_ABSOLUTE 3
# >> 12 POP_BLOCK
# >> 13 LOAD_CONST 0 (None)
# 16 RETURN_VALUE
dis.dis(bar)
# 0 SETUP_LOOP 3 (to 6)
#
# >> 3 JUMP_ABSOLUTE 3
# >> 6 LOAD_CONST 0 (None)
# 9 RETURN_VALUE
Edit: This is in Python 2.7.1. d0mine pointed out that the discrepancy is no longer the case in Python 3. Good to know. :)There is no difference on Python 3:
>>> dis.dis(foo)
2 0 SETUP_LOOP 3 (to 6)
3 >> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
>>> dis.dis(bar)
2 0 SETUP_LOOP 3 (to 6)
3 >> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
Lists, or any iterable, can be reverse-sorted with reversed(sorted(my_list)). That'll give you an iterator, though you can call list() on the result if you need it.
"while True" should be used in-place of "while 1". Reads better.
In Python 2, xrange() is preferred over range() when looping - it won't create an in-memory list of integers, and behaves mostly the same as range but for a few edge cases. Python 3 renamed xrange() to range(), and removed the original range() function.