python列表怎么写
首先,我们需要明确的一点就是Python是没有数组这一概念的,,但是Python中有一种比数组还要厉害的东西——列表,它的功能比数组更加强大。
2、列表操作简介
(1)创建列表
初学Python还是建议大家使用IDLE进行程序的编写,所以本文中所有讲解均是在IDLE下完成的,创建列表的方法及显示结果如下:
>>>number=[1,2,3,4,'python学习网']
>>>number
[1,2,3,4,'python学习网']
在列表中可以包含整形、字符串、浮点型数据,还可以包含另一个列表。
(2)向列表中添加元素
向列表添加元素一共有append()、extend()和insert()三种方法,下面我将三种方法一一道来:
1)append()方法默认将元素添加到列表末尾,并且一次只能添加一个元素,操作如下:
>>>number=[0,1,2,3,4]
>>>number.append(5)
>>>number
[0,1,2,3,4,5]
2)extend()方法可以添加多个元素,但是必须以列表的形式添加,操作如下:
>>>number=[0,1,2,3,4]
>>>number.extend([5,6])
>>>number
[0,1,2,3,4,5,6]
3)大家有没有发现前两种方法均将元素添加到列表末尾,如果想插队的话就需要使用insert()方法了,操作如下:
>>>number=[0,1,2,3,4]
>>>number.insert(2,1)
>>>number
[0,1,1,2,3,4]
insert(2,1)中2指位置,1是需要添加的元素(列表第一个元素所在位置为0)。
以上内容为大家介绍了python培训之列表怎么写,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






