How to understand this result?

I am new to Python. Here's the question I have about lists: They say that lists are mutable and tuples are immutable. But when I write the following:

L1 = [1, 2, 3]
L2 = (L1, L1)
L1[1] = 5
print L2

result

([1, 5, 3], [1, 5, 3])

instead

([1, 2, 3], [1, 2, 3])

But it L2is a tuple, and tuples are immutable. Why L1does changing the value also change the value L2?

+5
source share
7 answers

From the Python documentation (http://docs.python.org/reference/datamodel.html) note:

, ; , , , . , , , .

+7

, . L1 (), . L1, , .

"", , , , . , .

+4

, , .

(L1), (, ).

,

  L2[1] = 5

, .

, , , , ( , 5). .

, "" .

EDIT ( OP ):

, , , :

L=range(5)
s = (L, L[:]) # a reference to the original list and a copy

s
([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])

L [2]

L[2] = 'a'

:

s
([0, 1, 'a', 3, 4], [0, 1, 2, 3, 4])  # copy is not changed

, "2-" , .

,

L=range(5)

s = (L[:], L[:])

now 
L[2] = 'a'

, L

s
 ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])

, .

+4

, : L2 - L1 ( , , ), L1 . L1, L2, , L2.

+2

deepcopy =:

import deepcopy
  L2 = deepcopy (L1)

+2

, ( , ). , ( ), . .

+1

, , : , . , , . , , , .

Python, , , int, , , , , .

set(), , , :

>>> L=range(5)
>>> s = (L, L[:]) # a reference to the original list and a copy
>>> set(1, 2, s)
>>> set((1, 2, s))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

a set , , s, TypeError.

0

All Articles