python 元组的概念与基本用法

# -*-coding:utf-8 -*-
# @Time :  16:00
# @Author: 黄荣津
# @File : 17.什么是元组.py
# @Software: PyCharm

'''不可变序列,可变序列 根据id地址判断'''

#可变序列 列表,字典
lst=[10,20,45]
print(id(lst))
lst.append(330)
print(id(lst))

'''不可变序列,字符串,元组'''
s='hello'
print(id(s))
s=s+'world'
print(id(s))
print(s)
# -*-coding:utf-8 -*-
# @Time :  16:06
# @Author: 黄荣津
# @File : 18.元组的创建方式.py
# @Software: PyCharm

'''第一种,使用()'''
t=('python','world',98)
print(t)
print(type(t)) #<class 'tuple'>

'''第二种,使用内置函数tuple()'''
t1=tuple(('python','world',98))
print(t1)
print(type(t1))

#只包含一个元组的元素需要使用逗号和小括号
t2=(10,)
print(t2)
print(type(t2))

'''空列表的创建方式'''
'''空字典的创建方式'''
'''空元组的创建方式'''

lst=[]
lst1=list()

d={}
d1=dict()

t4=()
t5=tuple()

print('空列表',lst,lst1)
print('空字典',d,d1)
print('空元组',t4,t5)

# -*-coding:utf-8 -*-
# @Time :  16:23
# @Author: 黄荣津
# @File : 19.为什么将元组设计成不可变序列.py
# @Software: PyCharm

t=(10,[20,30],90)
print(t)
print(type(t))
print(t[0],type(t[0]),id(t[0]))
print(t[1],type(t[1]),id(t[1]))
print(t[2],type(t[2]),id(t[2]))

'''尝试将t[1]修改为100'''
# t[1]=100 #元组是不可以修改元素的

'''由于[20,30]是列表,而列表是可变序列,所以可以向列表中添加元素,列表的内存地址不变'''

t[1].append(100)
print(t)
print(id(t[1]))

# -*-coding:utf-8 -*-
# @Time :  16:37
# @Author: 黄荣津
# @File : 20.元组的遍历.py
# @Software: PyCharm

t=('python','hello',98)

'''第一种方式使用索引'''
print(t[0])
print(t[1])
print(t[2])
# print(t[3]) #IndexError: tuple index out of range

'''第二种遍历元组'''
for item in t:
    print(item)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值