I want to know if it's possible do that:
a = [0, 1, 2, 3, 4]
b = a[2:]
b[0] = -1
print(a)
print(b)
and get this:
[0, 1, -1, 3, 4]
[-1, 3, 4]
Normally, you will get this:
[0, 1, 2, 3, 4]
[-1, 3, 4]
I want to know if it's possible do that:
a = [0, 1, 2, 3, 4]
b = a[2:]
b[0] = -1
print(a)
print(b)
and get this:
[0, 1, -1, 3, 4]
[-1, 3, 4]
Normally, you will get this:
[0, 1, 2, 3, 4]
[-1, 3, 4]
Briefly explain what I understand this, let me know if I make any mistakes.
The answer is NO.
In python, the variable is a tag linked to the object. If we do
a = [0, 1, 2, 3, 4]
b = a
id(a) #199598920
id(b) #199598920
The b
is just a name tag name linked to the object.It shares the same object with a
To your question,
a = [0, 1, 2, 3, 4]
id(a) #199598920
a[2:] # [2, 3, 4]
id(a[2:]) #199581576
a[2:]
gives us a slice of a list by creating a new list and copying a part of the first list into the new list.
In this case, you cannot automatically update you b[0]
and list a
No, with plain list
s this is not possible because slicing returns a shallow copy of the slice.
However if you have NumPy it's possible because there slices of an array
return views not copies:
import numpy as np
a = np.array([0, 1, 2, 3, 4])
b = a[2:]
b[0] = -1
print(a) # [ 0 1 -1 3 4]
print(b) # [-1 3 4]
Do you mean something like that? ;)
a = [0, 1, 2, 3, 4]
b = a[2:]
b[0] = a[2] = -1
print(a)
print(b)