Link to an item in a list

I'm a little confused about how python handles a link to an item in a list, given 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 the first example, the contents in list a are changed; while in the second example, the contents of the list a are not changed. Why is this?

+4
source share
1 answer

Let's start with the second case. You write

c = random.choice(a)

therefore the name cbinds to some element a, then

c = b

therefore, the name is cattached to another object (to which the name refers b- float 0.1).


Now in the first case. You start with

c = random.choice(a)

, c a, .

c[:] = b

, , c, - . , c.


, , . , .

+3

Source: https://habr.com/ru/post/1653951/


All Articles