python 可變資料型別 不可變資料型別

2021-09-24 16:00:32 字數 741 閱讀 3621

在python中,資料型別分為可變資料型別和不可變資料型別,不可變資料型別包括string,int,float,tuple,可變資料型別包括list,dict。

所謂的可變與不可變,舉例如下:

>>> a = "test"

>>> print a[0]

t>>> a[0] = 1

traceback (most recent call last):

file "", line 1, in typeerror: 'str' object does not support item assignment

>>> a = [1, 2, 34]

>>> print a[0]

1>>> a[0] = 4

>>> a

[4, 2, 34]

>>>

因為字串是不可變物件,所以使用字串的內建方法replace()等並非改變原字串,而是新建立了乙個新的字串。

>>> a = "hello world"

>>> a.replace("world", "python")

'hello python'

>>> a

'hello world'

>>> a = a.replace("world", "python")

>>> a

'hello python'

>>>

python 可變資料型別 不可變資料型別

在python中,資料型別分為可變資料型別和不可變資料型別,不可變資料型別包括string,int,float,tuple,可變資料型別包括list,dict。所謂的可變與不可變,舉例如下 a test print a 0 t a 0 1 traceback most recent call las...

python 可變資料型別和不可變資料型別

不可變資料型別更改後位址發生變化,可變資料型別更改後位址不發生變化。看 說話 a 1 int b string string c 1,2 tuple print type a id a print type b id b print type c id c a 1b 1 c 3 4 print a,...

Python 可變資料型別和不可變資料型別

python的資料儲存在記憶體裡,該資料分為可變資料型別和不可變資料型別 不可變資料型別 字串,數字,元祖 可變資料型別 列表,字典,集合 nums 1 2,3 nums bk nums nums 0 0print nums nums print nums bk nums bk print form...