04 python基础三--使用list和tuple

1 list -- 列表

  • list是python内置的一种数据类型
  • list是一种有序的集合,可以随时添加和删除其中的元素
  • list用[ ]定义
>>> classmates = ['wangerxiao', 'daniu', 'xionger']
>>> classmates
['wangerxiao', 'daniu', 'xionger']

#classmates就是一个list,用len()函数可以获得list元素的个数
>>> len(classmates)
3

#可以通过索引访问list中的每个位置的元素,**注意:索引是从0开始的**
>>> classmates[0]
'wangerxiao'
>>> classmates[1]
'daniu'
>>> classmates[2]
'xionger'
#list也支持反向索引
>>> classmates[-1]
'xionger'
>>> classmates[-2]
'daniu'
>>> classmates[-3]
'wangerxiao'

以上实现了对list的赋值与读取,接下来是实现list的元素添加和删除

# 1.追加元素到末尾
>>> classmates.append('Bob')
>>> classmates
['wangerxiao', 'daniu', 'xionger', 'Bob']
# 2.追加元素到指定位置
>>> classmates.insert(1,'fanbingbing')
>>> classmates
['wangerxiao', 'fanbingbing', 'daniu', 'xionger', 'Bob']
# 3.删除末尾元素
>>> classmates.pop()
'Bob'
>>> classmates
['wangerxiao', 'fanbingbing', 'daniu', 'xionger']
# 4.删除指定位置元素
>>> classmates.pop(1)
'fanbingbing'
>>> classmates
['wangerxiao', 'daniu', 'xionger']

其他

# 1.替换指定位置元素,直接指定索引赋值即可
>>> classmates[1] = 'Susan'
>>> classmates
['wangerxiao', 'Susan', 'xionger']
# 2.list中的元素可以是多样化的
>>> list = [True, 123, 'aaa']
>>> list
[True, 123, 'aaa']
>>> newList = [123, False, list]
>>> newList
[123, False, [True, 123, 'aaa']]
>>> len(newList)
3
# 3.list也可以为空
>>> L = []
>>> len(L)
0

2 tuple -- 元组

  • tuple是python提供的另一种有序列表,与list类似
  • 但是tuple一旦初始化就不能修改
  • tuple不可变实际是指每个元素的指向不变
  • tuple用()定义
  • 可以正常使用索引读取值,但不能赋值
  • tuple意义在于:由于它的不可变性,所以代码更安全。如果有可能,能用tuple则不用list
  • tuple只有一个元素时必须加一个逗号,消除歧义
# >>> classmates = ('fan','zhao','liu')
>>> classmates
('fan', 'zhao', 'liu')
>>> T = (123,)
>>> T
(123,)

3 小结

list和tuple是Python内置的有序集合,一个可变,一个不可变。根据需要来选择使用它们。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、python 变量和数据类型 1.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序...
    绩重KF阅读 1,772评论 0 1
  • Python创建List Python创建list Python内置的一种数据类型是列表:list。list是一种...
    极客小寨阅读 497评论 0 0
  • 本教程基于Python 3,参考 A Byte of Python v1.92(for Python 3.0) 以...
    yuhuan121阅读 3,095评论 1 6
  • 我喜欢猫咪 以后我养只猫咪 你就负责养我 希望我们有一个温馨的小家 里面有我喜欢的阳台 还有一间光线充足的书房 我...
    拜星月慢阅读 314评论 0 9
  • 人类社会是由每个不同的个体组成的。而我们人类可以说每个人都有自己的性格特点,每个人都有自己的个性,但同时也存在共性...
    摆渡精灵阅读 210评论 0 0