如何在Python中向列表添加元素(append、extend和insert)
时间:2020-03-05 15:31:28 来源:igfitidea点击:
使用Python中的列表时,通常需要向列表添加新元素。
Python list数据类型有三种添加元素的方法:
append()—将单个元素追加到列表中。
extend()—将iterable的元素追加到列表中。
insert()—在列表的给定位置插入单个项。
这三个方法都会就地修改列表并返回None。
Python列表append()
方法的作用是:将一个元素添加到列表的末尾。
append()方法的语法如下:
list.append(element)
其中,element是要添加到列表中的元素。
下面是一个例子:
characters = ['Tokyo', 'Lisbon', 'Moscow', 'Berlin'] characters.append('Nairobi') print('Updated list:', characters)
Updated list: ['Tokyo', 'Lisbon', 'Moscow', 'Berlin', 'Nairobi']
元素参数可以是任何数据类型的对象:
odd_numbers = [1, 3, 5, 7] even_numbers = [2, 4, 6] odd_numbers.append(even_numbers) print('Updated list:', odd_numbers)
列表偶数作为单个元素添加到奇数个数列表中。
Updated list: [1, 3, 5, 7, [2, 4, 6]]
Python列表extend()
方法的作用是:将iterable的所有元素都放到列表的末尾。
extend()方法的语法如下:
list.extend(iterable)
其中,iterable是要添加到列表中的iterable。
characters = ['Tokyo', 'Lisbon', 'Moscow', 'Berlin'] new_characters = ['Nairobi', 'Denver', 'Rio'] characters.extend(new_characters) print('Updated list:', characters)
Updated list: ['Tokyo', 'Lisbon', 'Moscow', 'Berlin', 'Nairobi', 'Denver', 'Rio']
参数可以是任何类型的iterable:
animals = ['dog', 'cat'] # tuple mammals = ('tiger', 'elephant') animals.extend(mammals) print('Updated list:', animals) # dictionary birds = {'owl': 1, 'parrot': 2} animals.extend(birds) print('Updated list:', animals)
Updated list: ['dog', 'cat', 'tiger', 'elephant'] Updated list: ['dog', 'cat', 'tiger', 'elephant', 'owl', 'parrot']
Python列表插入insert()
方法的作用是:在指定的索引处向列表中添加一个元素。
insert()方法的语法如下:
list.insert(index, element)
其中,index是要在其前面插入的元素的索引,元素是要插入到列表中的元素。
在Python中,列表索引以0开头。
下面是一个例子:
fruits = ['raspberry', 'strawberry', 'blueberry'] fruits.insert(1, 'cranberry') print('Updated list:', fruits)
Updated list: ['raspberry', 'cranberry', 'strawberry', 'blueberry']
元素参数可以是任何数据类型的对象:
numbers = [10, 15, 20, 25] squares = [1, 4, 9] numbers.insert(2, squares) print('Updated list:', numbers)
列表方块作为单个元素插入到数字列表中。
Updated list: [10, 15, [1, 4, 9], 20, 25]