Python 创建空的list,以及append用法讲解

yipeiwu_com6年前Python基础

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

以上这篇Python 创建空的list,以及append用法讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中的rfind()方法使用详解

 rfind()方法返回所在子str 被找到的最后一个索引,或者-1,如果没有这样的索引不存在,可选择限制搜索字符串string[beg:end]. 语法 以下是rfind()...

python多线程threading.Lock锁用法实例

本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考。具体分析如下: python的锁可以独立提取出来 复制代码 代码如下:mutex = th...

python读取excel指定列数据并写入到新的excel方法

如下所示: #encoding=utf-8 import xlrd from xlwt import * #------------------读数据----------------...

Python语言的面相对象编程方式初步学习

词语练习 class:告诉python创造一个新的东西 object:两个意思:最基本的东西和任何实例化的东西。 instance:创建一个类得到的东西。 def:在类...

python字符串常用方法

1、 isalnum() :判断字符串所有的字符都是字母或者数字。返回true和false In [1]: str1='jiangwei520' In [2]: str2='jian...