天天看點

Python: 建立空的list,以及append用法

Python中list的用法:如何建立list,如何表達list中的元素,如何修改和删除list

運作環境:Python 3.6.2 0.空list的建立:

l = list()

或者:

l = []

1.list中元素的建立和表達 fruits = ['apple', 'banana', 'pear', 'grapes', 'pineapple', 'watermelon'] fruits[2] #從0開始數起,第三個元素 pear

2.list中元素的更改 fruits[2] = 'tomato' print(fruits) ['apple', 'banana', 'tomato', 'grapes', 'pineapple', 'watermelon']

3.在list末尾增加更多元素 fruits.append('eggplant') print(fruits) ['apple', 'banana', 'tomato', 'grapes', 'pineapple', 'watermelon', 'eggplant']

4.如何截取list中的某一段 print(fruit[: 2]) #從list的首元素開始截取,截取到位置'3',但不包括第3個元素 ['apple', 'banana']

5. 如何更改list中連續的元素 fruits[:2] = ['a', 'b'] print(fruits) ['a', 'b', 'tomato', 'grapes', 'pineapple', 'watermelon', 'eggplant']

6.如何删除list中某段元素,或者全部list fruits[:2] = [] #删除前兩個元素 print(fruits) ['tomato', 'grapes', 'pineapple', 'watermelon', 'eggplant'] fruits[:] = [] #删除全部list元素 []