Python creates an empty list and explains the usage of append

不言
Release: 2018-05-04 14:11:55
Original
3859 people have browsed it

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()
Copy after login

Or:

l = []
Copy after login

1.Creation and expression of elements in list

##

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

2.Change of elements in list

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

3. Add more elements to the end of the list

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

4. How to intercept a certain paragraph in the list

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

5. How to change consecutive elements in the list

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

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元素
[]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template