提示:python版本爲2.7,windows系統python
1.元組(Tuple)shell
Tuple,與List相似,可是Tuple一旦初始化以後就不能修改了,沒有增長、刪除、修改元素。windows
1 >>> colors = ('red', 'orange', 'yello') 2 >>> colors 3 ('red', 'orange', 'yello') 4 >>> type(colors) 5 <type 'tuple'>
空元組spa
1 >>> color = () 2 >>> color 3 ()
1個元素code
1 >>> color = (1) #這和數學的小括號同樣,因此當只有一個元素時,在末尾要加逗號 2 >>> color 3 1 4 >>> color = (1,) #是這種 5 >>> color 6 (1,)
修改元素,不能修改,也沒有添加、刪除方法blog
1 >>> colors[0] = 'white' 2 3 Traceback (most recent call last): 4 File "<pyshell#18>", line 1, in <module> 5 colors[0] = 'white' 6 TypeError: 'tuple' object does not support item assignment
其餘與List相似數學
1 >>> colors[0] 2 'red' 3 >>> colors[-1] 4 'yello' 5 >>> colors[0:1] 6 ('red',) 7 >>> colors[-1:-2] 8 () 9 >>> colors[-1:] 10 ('yello',) 11 >>> colors[-1:1] 12 () 13 >>> colors[-1:-1] 14 () 15 >>> colors[-2:-1] 16 ('orange',) 17 >>> colors[-3:-2] 18 ('red',)
當元組中有List時it
1 >>> test = ('a', 'b', 'c', ['d', 'e', 'f']) 2 >>> test[3] 3 ['d', 'e', 'f'] 4 >>> type(test[3]) 5 <type 'list'> 6 >>> test[3] = ['d'] #並不能修改List 7 8 Traceback (most recent call last): 9 File "<pyshell#38>", line 1, in <module> 10 test[3] = ['d'] 11 TypeError: 'tuple' object does not support item assignment 12 13 #能夠修改List的元素 14 >>> test[3][0] = 'g' 15 >>> test[3][1] = 'h' 16 >>> test[3][2] = 'i' 17 >>> test 18 ('a', 'b', 'c', ['g', 'h', 'i']) 19 #刪除List元素 20 >>> test[3].pop() 21 'i' 22 >>> test 23 ('a', 'b', 'c', ['g', 'h'])
其實,Tuple的不能修改是指每一個元素的指向地址不變,指向'red'後不能改爲指向'white',指向List時,List不能變成其餘元素,可是List中的元素能夠改變ast