I am new to python and noticed something. My run time was significantly lower when i used ['a' for i in range(10)] compared to ['a']*10. Can someone please explain why this happens?
Asked
Active
Viewed 212 times
-2
-
1Well, `['a']*10` should be faster. In this case, there is no difference, but in general, it is very different. See: https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – juanpa.arrivillaga Jul 21 '21 at 05:30
-
1Show us your benchmark code. Several of us are dubious of your results. – Tim Roberts Jul 21 '21 at 05:35
-
it was used in a LC question. the run time was slower if i declared the array using for loop. – user14531552 Jul 21 '21 at 06:07
1 Answers
0
['a' for i in range(10)]
executes the following in Python:
- Create a range
- Iterate the range, and for each iteration:
- Assign the iterated value to a locally defined variable
i
- Produce
'a'
- Assign the iterated value to a locally defined variable
- Collect the produced strings into a list
['a']*10
executes the following:
- Produce
'a'
(once) - Collect the given number of occurrences of
'a'
into a list
This is simplified, but it is clear that the second version:
- has no need of explicitly creating a (range) iterator;
- has no need of defining a local variable
i
; - has no iteration that is explicitly running as Python code; the iteration only happens in lower-level, compiled code.

trincot
- 317,000
- 35
- 244
- 286