可变和不可变类型¶

列表是可变的(Mutable)¶

In [1]:

  1. a = [1,2,3,4]
  2. a

Out[1]:

  1. [1, 2, 3, 4]

通过索引改变:

In [2]:

  1. a[0] = 100
  2. a

Out[2]:

  1. [100, 2, 3, 4]

通过方法改变:

In [3]:

  1. a.insert(3, 200)
  2. a

Out[3]:

  1. [100, 2, 3, 200, 4]

In [4]:

  1. a.sort()
  2. a

Out[4]:

  1. [2, 3, 4, 100, 200]

字符串是不可变的(Immutable)¶

In [5]:

  1. s = "hello world"
  2. s

Out[5]:

  1. 'hello world'

通过索引改变会报错:

In [6]:

  1. s[0] = 'z'
  1. ---------------------------------------------------------------------------
  2. TypeError Traceback (most recent call last)
  3. <ipython-input-6-83b06971f05e> in <module>()
  4. ----> 1 s[0] = 'z'
  5.  
  6. TypeError: 'str' object does not support item assignment

字符串方法只是返回一个新字符串,并不改变原来的值:

In [7]:

  1. print s.replace('world', 'Mars')
  2. print s
  1. hello Mars
  2. hello world

如果想改变字符串的值,可以用重新赋值的方法:

In [8]:

  1. s = "hello world"
  2. s = s.replace('world', 'Mars')
  3. print s
  1. hello Mars

或者用 bytearray 代替字符串:

In [9]:

  1. s = bytearray('abcde')
  2. s[1:3] = '12'
  3. s

Out[9]:

  1. bytearray(b'a12de')

数据类型分类:

可变数据类型 不可变数据类型
list, dictionary, set, numpy array, user defined objects integer, float, long, complex, string, tuple, frozenset

字符串不可变的原因¶

其一,列表可以通过以下的方法改变,而字符串不支持这样的变化。

In [10]:

  1. a = [1, 2, 3, 4]
  2. b = a

此时, ab 指向同一块区域,改变 b 的值, a 也会同时改变:

In [11]:

  1. b[0] = 100
  2. a

Out[11]:

  1. [100, 2, 3, 4]

其二,是字符串与整数浮点数一样被认为是基本类型,而基本类型在Python中是不可变的。

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/02-python-essentials/02.07-mutable-and-immutable-data-types.ipynb