Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a value to an element of a slice in Python

This is a simple question about how Python handles data and variables. I've done a lot of experimenting and have Python mostly figured out, except this keeps tripping me up:

[edit: I separated and rearranged the examples for clarity]

Example 1:

>>> a = [[1], 2]
>>> a[0:1]
[[1]]
>>> a[0:1] = [[5]]
>>> a
[[5], 2] # The assignment worked.

Example 2:

>>> a = [[1], 2]
>>> a[0:1][0]
[1]
>>> a[0:1][0] = [5]
>>> a
[[1], 2] # No change?

Example 3:

>>> a = [[1], 2]
>>> a[0:1][0][0]
1
>>> a[0:1][0][0] = 5
>>> a
[[5], 2] # Why now?

Can anybody explain to me what's going on here?

So far the answers seem to claim that a[0:1] returns a new list containing a reference to the first element of a. But I don't see how that explains Example 1.

like image 290
dln385 Avatar asked Oct 29 '10 20:10

dln385


1 Answers

a[0:1] is returning a new array which contains a reference to the array [1], thus you end up modifying the inner array via a reference call.

The reason the first case doesn't modify the [1] array is that you're assigning the copied outer array a new inner array value.

Bottom line - a[0:1] returns a copy of the data, but the inner data is not copied.

like image 142
koblas Avatar answered Nov 09 '22 11:11

koblas