python元组

元组tumple

    • tumple_python
      • 1.元组的创建
      • 2.元组是不可变序列
      • 3.元组的遍历

tumple_python

-元组(tuple)是是一个有序、不可变的序列。元组用小括号 () 表示,其中的元素可以是任意类型,并且可以通过索引访问。

  • 不可变序列与可变序列
    1>不可变序列(没有增、删、改的操作):字符串、元组
    2>可变序列:列表、字典(可以对序列执行增、删、改的操作,对象地址不发生改变):列表、字典

1.元组的创建

  • 直接小括号
t = ('Python', 'world', 98)
t1 = 'Python', 'world', 98  # 可省略小括号
  • 使用内置函数tumple()
t1 = tuple(('Python', 'world', 98))
  • 只包含一个元组的元素需要使用逗号和小括号
t3 = ('python')
print(type(t3))  # 
t4 = ('python',)
print(type(t4))  # 
  • 空元组
t5 = ()
t6 = tuple()

2.元组是不可变序列

  • 元组中存储的是对象的引用
  • a)如果元组中的对象本身是不可变对象,则不能再引用其他对象
  • b)如果元组中的对象是可变对象,则可变对象的引用不允许改变,但数据可以改变
    python元组_第1张图片
t = (10, [20, 30], 9)

print(t)  # (10, [20, 30], 9)
print(type(t))  # 
print(t[0], type(t[0]), id(t[0]))  # 10  140706566772672
print(t[1], type(t[1]), id(t[1]))  # [20, 30]  2095242058432
print(t[2], type(t[2]), id(t[2]))  # 9  140706566772640

# t[0] = 1  # 报错
# t[1] = 100  # 报错(元组不允许修改):'tuple' object does not support item assignment
'''由于[20, 30]列表,而列表是可变序列,所以可以向列表中添加元素,而列表的内存地址不变'''
t[1].append(100)
print(t[1], id(t[1]))  # [20, 30, 100] 2204931500480

3.元组的遍历

t = ('Python', 'world', 98)

'''第一种获取元组元素的方式,使用索引'''
print(t[0])
print(t[1])
print(t[2])

'''遍历元组'''
for item in t:
    print(item)
'''
Python
world
98
'''

你可能感兴趣的:(python基础,python,开发语言)