+ 1
Please help me to understand output
l1=[1,2,3,4] l2=l1 l1[2]=10 print(l2[2]) output: 10 why l2[2] changed to 10 while. only change done is with l1
4 Answers
+ 2
In general, doing l2 = l1[:] is a quick way to solve the problem just as VcC said, but be careful because when you do that you create a list with a copy of each object in the original list. That is not a problem if they are numbers or strings, but if one of the elements of the list is another list, the copy you create of that list still has the same objects, pointing at the same space in memory as the original one. So, in those cases, you need to copy element by element with a loop or a list comprehension.
+ 5
l2 and l1 are pointing to the same memory place, ie the same list.
if you dont want this do l2=l1[:]
+ 1
So l2 is just a pointer ?
0
In Python, whenever you create a variable, that variable doesnt contain directly the value you have asigned It. Instead, it contains the direction in memory where that value is stored. This is done so that regardless of the size of what you are storing, variables always have the same size. This makes the allocation, extraction and length of the list, values that can be calculated easily in constant time (regardless of the amount of elements in the list). So, when you create a list, the variable naming that list points to somewhere in memory where the first element of the list is, thats why when you do l2 = l1, l2 takes as value the same direction l1 was pointing to.