What’s the difference between
lst = range(100)
and
lst[:] = range(100)
Before that assignment the lst variable was already assigned to a list:
lst = [1, 2, 3]
lst = range(100)
or
lst = [1, 2, 3]
lst[:] = range(100)
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.
When you do
You’re pointing the name
lstat an object. It doesn’t change the old objectlstused to point to in any way, though if nothing else pointed to that object its reference count will drop to zero and it will get deleted.When you do
You’re iterating over
whatever, creating an intermediate tuple, and assigning each item of the tuple to an index in the already existinglstobject. That means if multiple names point to the same object, you will see the change reflected when you reference any of the names, just as if you useappendorextendor any of the other in-place operations.An example of the difference:
When it comes to speed, slice assignment is slower. See Python Slice Assignment Memory Usage for more information about its memory usage.