0

Consider:

a = [1, 2, 3]

When I slice it I get a new list b:

b = a[:2]

If I now alter list b:

b[0] = 0

I get a = [1, 2, 3] and b = [0, 2]. Why doesn't the a list get altered as well? I know that slicing creates a new list object, but why is it not the object of the same elements as the inital object? How can I slice a so that:

a = [1, 2, 3]
b = a[:2]
b[0] = 0

Results in a = [0, 2, 3] and b = [0, 2].

2 Answers2

0

You could try slicing later:

a = [1, 2, 3]
b = a
b[0] = 0
b = b[:2]
print(a, b)

Output:

[0, 2, 3] [0, 2]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

The notation [:2] is making a shallow copy of the list a upto the 3rd index.

For instance, if you would have ever seen programmers doing [:] while iterating over a list, they are creating the shallow copy of the list. Similarly, the above notation makes a copy of the list upto the 3rd index so you get something as:

[1, 2]

To get the result, you can do:

a = [1, 2, 3]
b = a
b[0] =0 

In here b = a is not making a copy the list. Both a, b point to the same list in the memory.

If you change either of the 2, it will reflect in both of them. Later, you can slice b by [:2]