4

I am a little confused about how python deal with reference to an element in a list, considering these two examples:

First example:

import random
a = [[1,2],[3,4],[5,6],[7,8]]
b = [0.1,0.2]
c = random.choice(a)
c[:] = b
print(a)

Second example:

import random
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = 0.1
c = random.choice(a)
c = b
print(a)

In first example, the content in list a is changed; while in the second example, the content of list a is not changed. Why is that?

SimonInNYC
  • 400
  • 3
  • 15

1 Answers1

3

Let's start with the second case. You write

c = random.choice(a)

so the name c gets bound to some element of a, then

c = b

so the name c gets bound to some other object (the one to which the name b is referring - the float 0.1).


Now to the first case. You start with

c = random.choice(a)

So the name c gets bound to an object in a, which is a list itself. Then you write

c[:] = b

which means, replace all items in the list bound to by the name c, by some other list. In fact, this is called slice assignment, and is basically syntactic sugar for calling a method of the object to which c is bound.


The difference, then, is that in the first case, it doesn't just bind a name first to one object, then to another. It binds a name to a list, then uses this name to indirectly call a method of the list.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185