列表
Python 内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中
的元素
语法以及定义方式:
a = [] : []------方括号表示集合;【】[]
len(classmates)-1: 表示列表当中最后一个元素的索引。
L[3] = L[len(classmates)-1]
# 超出列表索引会报错 eg: classmate[4]报错,超出索引
# IndexError: list index out of range
添加元素方法:
append() : 在列表最后插入元素 (一个参数)
insert():在指定索引处,插入元素。(两个参数)
classmates = [‘张三’, ‘李四’, ‘王五’,‘小明’]
print(len(classmates))
# classmates的长度是多少?
# 超出列表索引会报错
# IndexError: list index out of range
# 如何将 '小红’加入当classmates这个列表当中
classmates.append(‘小红’)
# append(): 向列表当中添加元素。列表当中的方法,用’.'点,调用。
# append():添加的元素是在列表的最后。
#如何添加到列表的指定位置,eg:添加到第一个位置
# classmates.append(0,‘小白’)
# TypeError: append() takes exactly one argument (2 given)
#append(): 只能接受一个参数,我们给了它两个参数,所以会报错
classmates.insert(0,‘小白’)
# insert():在指定索引处,插入元素。
删除元素:
#pop() :删除列表当中最后一个元素
#pop(index): 删除指定索引的元素
classmates = [‘张三’, ‘李四’, ‘王五’,‘小明’]
print(classmates)
#删除元素
classmates.pop()
print(classmates)
classmates.pop(1)
print(classmates)
列表内置方法:
pop() :删除列表当中最后一个元素
pop(index): 删除指定索引的元素
append(value) : 在列表最后插入元素 (一个参数)
## insert(index,value):在指定索引处,插入元素。(两个参数)
列表插入删除练习:
fruit