Home  >  Article  >  Backend Development  >  Python creates an empty list and explains the usage of append

Python creates an empty list and explains the usage of append

不言
不言Original
2018-05-04 14:11:553774browse

This article mainly introduces how to create an empty list in Python and how to use append. It has certain reference value. Now I share it with you. Friends in need can refer to it

Usage of list in Python : How to create a list, how to express elements in the list, how to modify and delete the list

Running environment: Python 3.6.2

0. Creation of an empty list:

l = list()

Or:

l = []

1.Creation and expression of elements in list

##

fruits = ['apple', 'banana', 'pear', 'grapes', 'pineapple', 'watermelon']
fruits[2] #从0开始数起,第三个元素
pear

2.Change of elements in list

fruits[2] = 'tomato'
print(fruits)
['apple', 'banana', 'tomato', 'grapes', 'pineapple', 'watermelon']

3. Add more elements to the end of the list

fruits.append('eggplant')
print(fruits)
['apple', 'banana', 'tomato', 'grapes', 'pineapple', 'watermelon', 'eggplant']

4. How to intercept a certain paragraph in the list

print(fruit[: 2]) #从list的首元素开始截取,截取到位置'3',但不包括第3个元素
['apple', 'banana']

5. How to change consecutive elements in the list

fruits[:2] = ['a', 'b']
print(fruits)
['a', 'b', 'tomato', 'grapes', 'pineapple', 'watermelon', 'eggplant']

6 .How to delete a certain element in the list, or the entire list

fruits[:2] = [] #删除前两个元素
print(fruits)
['tomato', 'grapes', 'pineapple', 'watermelon', 'eggplant']
fruits[:] = [] #删除全部list元素
[]

Related recommendations:


Python implementation method of creating a list and adding elements to the list_python


##

The above is the detailed content of Python creates an empty list and explains the usage of append. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn