For lack of a better title, I want to find the most proper way to write (0, 0, 0, 0)
.
I am simply asking if (0,) * 4
is acceptable, and should it be done?
Are there any specific cases for this?
What if it could be either RGB, or RGBA? Should I do (0,) * n
?
If this were in a loop, how significant would the overhead be?
Thanks.
Disclaimer: I am not asking for opinions, I am asking for a general consensus, or any written specification. Do not give your sole opinion without any support, or this post runs the risk of being closed due to going off-topic.
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 liststuple([] for _ in range(n))
for tuple of listsNote 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