I have list of ints that looks like this:
a = [-10, -100, -1000, -2000, -3000]
I would like to create a new list from this list:
b = [-10, -100, -1000, -2000, -3000, -3000, -2000, -1000, -100, -10]
I know this is possible doing something like:
b = a[::-1]
res = a b
Is there a more efficient way of doing it though?
CodePudding user response:
You can remove the temporary variable b
so that there's no extra copy of a[::-1]
hanging around.
res = a a[::-1]
CodePudding user response:
So for this issue, the only 3 realistic solutions seem to be adding the reversed slice of a
, copying a
and extending it by the reversed slice, and unpacking a
along with unpacking reversed(a)
:
from timeit import timeit
setup = 'a = [-10, -100, -1000, -2000, -3000]'
print(timeit('a a[::-1]', setup))
print(timeit('a.copy().extend(a[::-1])', setup))
print(timeit('[*a, *reversed(a)]', setup))
And my results are:
0.5961677939922083
0.8394856759987306
0.8519255819992395
So in conclusion the former is definitely the most efficient approach.
As for if you had an iterable and wanted to do this you would be forced to consume it as there is no way to reverse an iterable without doing so. For instance:
a = (i%2 for i in range(100))
b = list(a)
reversed = a a[::-1]
Note for range
you can take slices of it, so no need to use list
on them:
print(*range(10)[::-1])
#9 8 7 6 5 4 3 2 1 0