If you had 100 zeroes to write in a tuple or list would you ask yourself this question?
Since the contents of the tuple
are immutable elements, it's equivalent (it's faster to parse - see the end of the post - and the intent is clearer) to do (0,) * 4
instead of (0,0,0,0)
. It's beginning to become ridiculous for 2 elements but that's just my opinion :).
If the number increases it may save some precious debugging time because you missed one count/paste.
For mutable types don't do that!, but you can do a similar thing: ex:
[[] for _ in range(n)]
for list of lists
tuple([] for _ in range(n))
for tuple of lists
Note that the (0,)*n
form is definitely faster to parse. It's tricky to time such constructs because doing this naively skips the parsing part. But using evil eval
helps in that case:
import time
n=100000
start_time = time.time()
for _ in range(n):
eval("(0)*50")
print(time.time()-start_time)
fifty_zeros_tuple = "({})".format("0,"*50) # generate (0,0,0,...) expression to pass to eval, not clocked to avoid bias
start_time = time.time()
for _ in range(n):
eval(fifty_zeros_tuple)
print(time.time()-start_time)
no photo-finish on the results, (0,)*50
is many times faster:
0.764380931854248
5.553457021713257