0

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]
rvcristiand
  • 442
  • 7
  • 19

3 Answers3

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

enter image description here


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.

enter image description here

In this case, you cannot automatically update you b[0] and list a

Mr_U4913
  • 1,294
  • 8
  • 12
  • I understood. It's not possible, I need coded it. Thank you ! – rvcristiand Jul 18 '17 at 00:11
  • Comparing the `id` of the original and the slice isn't conclusive - because even if they would share the underlying "data" the id has to be different (simply because one instance can't represent itself and a slice of itself). Otherwise great answer - I really like the images! :) – MSeifert Jul 18 '17 at 00:27
4

No, with plain lists 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]
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

Do you mean something like that? ;)

a = [0, 1, 2, 3, 4]
b = a[2:]
b[0] = a[2] = -1 
print(a)
print(b)
ZRTSIM
  • 75
  • 6