0

I am using python 2.7.6 and tried following code,

mylist1=["A1","A2","A3","A4","A5","A6","A7"]
print mylist1 #prints ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7']
mylist1[2:5]=["B3","B4","B5"]
print mylist1 #prints ['A1', 'A2', 'B3', 'B4', 'B5', 'A6', 'A7']
print mylist1[2:3][0] #prints B3
mylist1[2:5][0]="C5"
print mylist1 #prints ['A1', 'A2', 'B3', 'B4', 'B4', 'A6', 'A7']

I am able to modify list mylist1 using mylist1[2:5]=["B3","B4","B5"]

But Why statement mylist1[2:5][0]="C5" not changing list mylist1 ?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
MaYuRb
  • 9
  • 3
  • Related http://stackoverflow.com/questions/10155951/what-is-the-difference-between-slice-assignment-that-slices-the-whole-list-and-d – Mazdak Jul 06 '16 at 17:50

1 Answers1

0

Because slicing creates a shallow copy of your original list. See this answer for more details about shallow and deep copy. In simple terms, when you do

mylist1[2:5][0]="C5"

the interpreter creates a new list object with the 3rd, 4th and 5th element of mylist1. Then it assigns the string "C5" to its first element and because there is no reference to the new list object just created, it gets garbage-collected, leaving the original mylist1 intact.

Community
  • 1
  • 1
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75