|
repeat comprehension
20151017
Fill an array with 1 particular value
Via comprehension:
z1=[0 for x in range(20)]
z1
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Via built-in repeat:
z2=[0] * 20
Equal? yes.
z1==z2
True
Which one is faster?
timeit.timeit('z=[0 for x in range(100000)]',number=100)
0.8116392770316452
timeit.timeit('z=[0]*100000',number=100)
0.050275236018933356
The built-in repeat beats comprehension hands down!
| |