tuple和list的主要区别就是tuple里的元素的是不能改变的,即tuple时immutable的

#创建tuple
>>> tupa = (12 , 'ed' , 34)
>>> tupb = 134 , 'hf', 43
>>> tupc = (12 ,)   #一个元素的时候不能不写","
>>> print tupa,tupb, tupc
(12, 'ed', 34) (134, 'hf', 43) (12,)

#访问tuple
#tupb[1:2]包括第1个但不包括第2个,Python很多地方都是这样的
>>> print tupa[0],tupb[1:2], tupc[-1] , tupb[-2]
12 ('hf',) 12 hf

#更新tuple
#tuple是immutable的,里面的值不能更改
>>> tupa[0] = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: &#39;tuple&#39; object does not support item assignment

#合并tuple
>>> tupd = tupa + tupb
>>> print tupa, tupb, tupd
(12, &#39;ed&#39;, 34) (134, &#39;hf&#39;, 43) (12, &#39;ed&#39;, 34, 134, &#39;hf&#39;, 43)

#删除tuple
#tuple是immutable的,里面的值不能删除,只能使用del删除整个tuple
>>> del tupd[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: &#39;tuple&#39; object doesn&#39;t support item deletion
>>> del tupd
>>> print tupd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name &#39;tupd&#39; is not defined

基本操作

#测试tuple里元素的数目
>>> len(tupa)
3

#合并tuple
>>> print tupa+tupb
(12, &#39;ed&#39;, 34, 134, &#39;hf&#39;, 43)

#重复tuple
>>> print tupa*2, tupa[0]*3, tupa[1]*4
(12, &#39;ed&#39;, 34, 12, &#39;ed&#39;, 34) 36 edededed

#元素所属
>>> 12 in tupa
True
>>> 12 in tupa, 14 in tupa
(True, False)
>>> test = 12 in tupa
>>> print test
True
>>> test = 12 in tupa, 15 in tupa
>>> print test
(True, False)

#遍历元素
>>> for x in tupa:
...     print x
... 
12
ed
34

Built-in Tuple Functions

cmp()

Compares elements of both tuples.If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers.

  • If numbers, perform numeric coercion if necessary and compare.
  • If either element is a number, then the other element is "larger" (numbers are "smallest").
  • Otherwise, types are sorted alphabetically by name.

If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust both tuples and share the same data, the result is a tie, meaning that 0 is returned

Syntax&P

cmp(tuple1, tuple2)

eg

>>> cmp (tupa,tupb)
-1

len()

Returns the total length of the tuple.

Syntax&P

len(tuple)

eg

>>> len(tupa)
3

max()

Returns item from the tuple with max value.

Syntax&P

max(tuple)

eg

>>> max(tupa)
&#39;ed&#39;

min()

Returns item from the tuple with min value.

Syntax&P

min(tuple)

eg

>>> min(tupa)
12

tuple()

Converts a list into tuple

Syntax&P

tuple(seq)

eg

>>> lia=[12,14,&#39;12&#39;]
>>> print tuple(lia)
(12, 14, &#39;12&#39;)