# python tuple 操作

### python 串列與tuple

>>> a = [123, ‘abc’, [111,222], (333,444)]
>>> print a[0]
123
>>> print a[2][1]
222
>>> print a[3][1]
444

#### 相加

>>> a = [111,222] + [333,444] + [555,666]
>>> a
[111, 222, 333, 444, 555, 666]
>>>
>>> b = (‘aaa’,’bbb’) + (‘ccc’,’ddd’)
>>> b
(‘aaa’, ‘bbb’, ‘ccc’, ‘ddd’)

>>> c = a + b
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: can only concatenate list (not “tuple”) to list

>>> c = a + list(b)
>>> c
[111, 222, 333, 444, 555, 666, ‘aaa’, ‘bbb’, ‘ccc’, ‘ddd’]
>>>
>>> c = tuple(a) + b
>>> c
(111, 222, 333, 444, 555, 666, ‘aaa’, ‘bbb’, ‘ccc’, ‘ddd’)

#### 相乘

>>> a = [111,222]
>>> a * 3
[111, 222, 111, 222, 111, 222]
>>>
>>> b = (‘aaa’,’bbb’)
>>> b * 5
(‘aaa’, ‘bbb’, ‘aaa’, ‘bbb’, ‘aaa’, ‘bbb’, ‘aaa’, ‘bbb’, ‘aaa’, ‘bbb’)

#### 修改

>>> a = [123, ‘abc’, [111,222], (333,444)]
>>> a[1] = ‘xyz’
>>> a
[123, ‘xyz’, [111, 222], (333, 444)]

>>> a = [123, ‘abc’, [111,222], (333,444)]
>>> a[0:2] = [‘aaa’,’bbb’,’ccc’]
>>> a
[‘aaa’, ‘bbb’, ‘ccc’, [111, 222], (333, 444)]

#### 刪除

>>> a = [123, ‘abc’, [111,222], (333,444)]
>>> a[1:3] = []
>>> a
[123, (333, 444)]

>>> a = [123, ‘abc’, [111,222], (333,444)]
>>> del a[1:3]
>>> a
[123, (333, 444)]

>>> a = [123, ‘abc’, [111,222], (333,444)]
>>> a.remove(‘abc’)
>>> a
[123, [111, 222], (333, 444)]
>>>
>>> a.remove([111,222])
>>> a
[123, (333, 444)]

#### append與pop

>>> a = [123,456]
>>> a.append(789)
>>> a
[123, 456, 789]

>>> a = [111,222,333,444,555]
>>> a.pop()
555
>>> a
[111, 222, 333, 444]
>>> a.pop(0)
111
>>> a
[222, 333, 444]

#### 其他

>>> a = 111, 222, 333
>>> a
(111, 222, 333)

>>> a = 111,
>>> a
(111,)
>>> a = (111,)
>>> a
(111,)
>>> b = 111
>>> b
111
>>> b = (111)
>>> b
111
上例b因沒有加逗號，而被誤認為數字111

python因為有了串列與tuple，可以省掉很多製作資料結構所花費的心力，可以更專注在要解決的問題。有一個用法也很方便，就是要交換2個變數值，以傳統C語言的寫法可能會是:
temp = a;
a = b;
b = temp;

>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1

Like what you read? Give Steven Wang a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.