列表(List)

列表定义

列表是一个序列(sequence),我们可以理解为一个装数据的容器。

Python中,列表使用频率很频繁。可以以存储一串数据,存储的每一个数据,我们称之为 元素

列表的类型为list, 用一对[] 表示

names = ['itcast', 'itheima', 'bxg']
print(names)
print(type(names))

列表操作

列表长度

names = ['itcast', 'itheima', 'bxg']
print(len(names))
通过len函数获得列表的长度

访问元素

通过下标进行访问, 列表下标从0开始

names = ['itcast', 'itheima', 'bxg']
print(names[0])
print(names[1])
print(names[2])
print(names[-1])

Note

通过下标进行访问元素,下标从0开始。

下标也可以为负数,为 当前下标减去列表长度

超出长度,会有异常

增加元素

通过append函数添加元素

names = ['itcast', 'itheima', 'bxg']
names.append('czxy')
print(names)

通过insert函数插入指定位置

names = ['itcast', 'itheima', 'bxg']
names.insert(1, 'czxy')
print(names)

删除元素

通过remove函数移除指定元素

names = ['itcast', 'itheima', 'bxg']
names.remove('bxg')
print(names)

通过del函数移除指定下标

names = ['itcast', 'itheima', 'bxg']
del names[1]
print(names)

修改元素

通过索引来修改元素

names = ['itcast', 'itheima', 'bxg']
names[1] = 'czxy'
print(names)

索引

通过元素获得下标索引

names = ['itcast', 'itheima', 'bxg']
index = names.index('itheima')
print(index)

反转

names = ['itcast', 'itheima', 'bxg']
names.reverse()
print(names)

排序

升序

names = ['itcast', 'itheima', 'bxg']
names.sort()
print(names)

降序

names = ['itcast', 'itheima', 'bxg']
names.sort(reverse=True)
print(names)