I am a newbie to python,everywhere I read about list methods I see one thing
The slice method returns a “new” list
What is here meant by “new” list,and why is it faster then changing the original list?
Does it really matter if python manipulates the original list,I mean I cant use it anyway.
I hope that this helps explain what it means by making a new list:
When doing
listb = listayou are not making a new list, you are making an additional reference to the same list. This is shown by changing the first element in lista withlista[0] = 3, this also changes the first element in listb. However, when slicing lista into listc withlistc = lista[:]you are copying over the values. When changing the first element of lista back to 1 withlista[0] = 1, the first element of listc is still 3.For speed I would expect slicing to be slower but this should not be a consideration for which one to use. As I’ve shown they both have a very different implication and it depends on what you are going to do with the list, rather than on speed (this is in general. There are occasion where the speed might be important).