Yes, additional memory will be reserved for a new list object that is created only for slice.
However, the request object is discarded again after the length request. You simply created a list object to calculate how much half the list will be.
Memory allocation is relatively expensive, even if you drop the object again. This is what I had in mind while you are looking for a steady increase in memory. However, a transition list object may be, you still need to allocate memory for this object.
The cost immediately manifests itself when you use timeit to compare two approaches:
>>> import timeit >>> def calculate(alist): ... (1 + len(alist)) // 2 ... >>> def allocate(alist): ... len(alist[::2]) ... >>> testlist = range(10**5) >>> timeit.timeit('f(testlist)', 'from __main__ import testlist, calculate as f', number=10000) 0.003368854522705078 >>> timeit.timeit('f(testlist)', 'from __main__ import testlist, allocate as f', number=10000) 2.7687110900878906
A slice should only create a list object and copy half the links, but this operation takes 800 times longer, simply calculating the length from the existing list.
Note that I really had to reduce the number of timeit repetitions; by default, 1 million reps will take an additional 4.5 minutes. I was not going to wait so long, while the direct calculation took only 0.18 seconds.
source share