(四)元组

1.一个赋值---所谓"元"组,就是"圆括号"

>>> a="abc",123,['name','age']
>>> a
('abc', 123, ['name', 'age'])
>>> type(a)
# 这就是元组

  • 特点:不可修改,实际上是一个融合列表和字符串的杂交产物
# 重新赋值是不行的,但可以转为列表后,再修改
>>> a[0]='def'
Traceback (most recent call last):
  File "", line 1, in 
    a[0]='def'
TypeError: 'tuple' object does not support item assignment
>>> a.append('Jim Green')
Traceback (most recent call last):
  File "", line 1, in 
    a.append('Jim Green')
AttributeError: 'tuple' object has no attribute 'append'
>>> 

2.单个元素的注意事项---末尾要加逗号

>>> a=(2)
>>> type(a)

>>> b=(2,)
>>> type(b)

3.列表和元组之间的转换---list()和tuple():

>>> tuple1=(1,2,3,4,5)
>>> list1=list(tuple1)
>>> list1
[1, 2, 3, 4, 5]
>>> tuple2=tuple(list1)
>>> tuple2
(1, 2, 3, 4, 5)
# 值一样,但是不是同一个对象
>>> tuple1 is tuple2
False
>>> id(tuple1)
44426432
>>> id(tuple2)
51184128

你可能感兴趣的:((四)元组)