fcracker79
fcracker79

Reputation: 1218

Python: lists and copy of them

I can not explain the following behaviour:

l1 = [1, 2, 3, 4]
l1[:][0] = 888
print(l1) # [1, 2, 3, 4]
l1[:] = [9, 8, 7, 6]
print(l1) # [9, 8, 7, 6]

It seems to be that l1[:][0] refers to a copy, whereas l1[:] refers to the object itself.

Upvotes: 11

Views: 395

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43136

This is caused by python's feature that allows you to assign a list to a slice of another list, i.e.

l1 = [1,2,3,4]
l1[:2] = [9, 8]
print(l1)

will set l1's first two values to 9 and 8 respectively. Similarly,

l1[:] = [9, 8, 7, 6]

assigns new values to all elements of l1.


More info about assignments in the docs.

Upvotes: 13

Max Noel
Max Noel

Reputation: 8910

l1[:][0] = 888 first takes a slice of all the elements in l1 (l1[:]), which (as per list semantics) returns a new list object containing all the objects in l1 -- it's a shallow copy of l1.

It then replaces the first element of that copied list with the integer 888 ([0] = 888).

Then, the copied list is discarded because nothing is done with it.

Your second example l1[:] = [9, 8, 7, 6] replaces all the elements in l1 with those in the list [9, 8, 7, 6]. It's a slice assignment.

Upvotes: 7

Related Questions