列表不必有相同的数据类型。
创建空列表:
第一种:l = list()
第二种:l = []
创建有元素的列表:
cars = ['byd','audi','gelly','qirui','chengcheng']
print(cars[0])
列表中元素用中括号括起来,是有序的、索引自0开始、最后一个元素从-1开始,以此类推。
修改指定位置元素:
cars = ['byd','audi','gelly','qirui','chengcheng']
cars[2]='tesla'
print(cars)
在末尾增加元素append()方法:
cars = ['byd','audi','gelly','qirui','chengcheng']
cars.append('tesla')
print(cars)
列表中指定位置插入元素方法:
cars = ['byd','audi','gelly','qirui','chengcheng']
cars.insert(1,'tesla')
print(cars)
删除元素方法:
cars = ['byd','audi','gelly','qirui','chengcheng']
del cars[2]
print(cars)
删除元素并返回被删除的值(默认是删除末尾元素):
cars = ['byd','audi','gelly','qirui','chengcheng']
pop1 = cars.pop(1)
print(pop1)
print(cars)
结果:
audi
['byd', 'gelly', 'qirui', 'chengcheng']
del 和 pop 的区别在于删除之后是否还要继续使用这个被删除的元素。
根据值删除元素:
cars = ['byd','audi','gelly','qirui','chengcheng']
cars.remove('gelly')
print(cars)
结果:
['byd', 'audi', 'qirui', 'chengcheng']
remove只能删除一个元素,若列表中有多个值相同的元素,则需要循环删除。
列表清空的四种方法:
1 ls.clear()
2 del删除
3 赋值法 ls = []
4 乘以零 ls *= 0
#列表切片
players = ['charles','martina','michael','florence','eli','eli6','eli7','eli8','eli9','eli10','eli11']
print(players[0:3])
print(players[:4])
print(players[2:])
print(players[-3:])
print(players[0:len(players):2])
结果:
['charles', 'martina', 'michael']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli', 'eli6', 'eli7', 'eli8', 'eli9', 'eli10', 'eli11']
['eli9', 'eli10', 'eli11']
['charles', 'michael', 'eli', 'eli7', 'eli9', 'eli11']
#利用切片复制列表,不能直接用等号,那实际上两个列表指向了一个引用
players2 = players[:]
print('players2: ' , players2)