I have the following problem.
Given a list of integers
L, I need to generate all of the sublistsL[k:]for k in [0, len(L) - 1], without generating copies.
How do I accomplish this in Python? With a buffer object somehow?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The short answer
Slicing lists does not generate copies of the objects in the list; it just copies the references to them. That is the answer to the question as asked.
The long answer
Testing on mutable and immutable values
First, let’s test the basic claim. We can show that even in the case of immutable objects like integers, only the reference is copied. Here are three different integer objects, each with the same value:
They have the same value, but you can see they are three distinct objects because they have different
ids:When you slice them, the references remain the same. No new objects have been created:
Using different objects with the same value shows that the copy process doesn’t bother with interning — it just directly copies the references.
Testing with mutable values gives the same result:
Examining remaining memory overhead
Of course the references themselves are copied. Each one costs 8 bytes on a 64-bit machine. And each list has its own memory overhead of 72 bytes:
As Joe Pinsonault reminds us, that overhead adds up. And integer objects themselves are not very large — they are three times larger than references. So this saves you some memory in an absolute sense, but asymptotically, it might be nice to be able to have multiple lists that are “views” into the same memory.
Saving memory by using views
Unfortunately, Python provides no easy way to produce objects that are “views” into lists. Or perhaps I should say “fortunately”! It means you don’t have to worry about where a slice comes from; changes to the original won’t affect the slice. Overall, that makes reasoning about a program’s behavior much easier.
If you really want to save memory by working with views, consider using
numpyarrays. When you slice anumpyarray, the memory is shared between the slice and the original:What happens when we modify
aand look again atb?But this means you have to be sure that when you modify one object, you aren’t inadvertently modifying another. That’s the trade-off when you use
numpy: less work for the computer, and more work for the programmer!