list extend
时间: 2023-09-28 15:12:19 浏览: 23
Python's list extend() method adds the elements of one list to the end of another list.
Syntax:
```python
list1.extend(list2)
```
Here, list1 is the list to which the elements of list2 are added.
Example:
```python
fruits = ['apple', 'banana', 'cherry']
more_fruits = ['orange', 'peach', 'pear']
fruits.extend(more_fruits)
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange', 'peach', 'pear']
```
In this example, the elements of the list `more_fruits` are added to the end of the list `fruits` using the `extend()` method. The resulting list is `['apple', 'banana', 'cherry', 'orange', 'peach', 'pear']`.
相关问题
python list extend
Python中的列表(list)是一种有序、可变的数据结构,可以存储多个元素。列表的extend()方法用于在列表末尾一次性添加另一个可迭代对象中的所有元素。
具体来说,extend()方法接受一个可迭代对象作为参数,将该可迭代对象中的所有元素依次添加到列表中。如果可迭代对象是一个列表,那么它会被展开,将其中的元素逐个添加到原列表中。
下面是一个示例代码:
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # 输出:[1, 2, 3, 4, 5, 6]
```
在上面的例子中,我们首先创建了两个列表list1和list2。然后使用extend()方法将list2中的元素添加到list1的末尾,最终得到了一个包含所有元素的新列表。
需要注意的是,extend()方法会修改原列表,而不是创建一个新的列表。另外,extend()方法也可以接受其他类型的可迭代对象,比如字符串、元组等。
python list extend和append
Python的列表有extend和append两个方法。
extend方法用于将一个列表中的元素添加到另一个列表的尾部,相当于把两个列表合并成一个。例如:
```
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # 输出为 [1, 2, 3, 4, 5, 6]
```
append方法用于将一个元素添加到列表的尾部。例如:
```
list1 = [1, 2, 3]
list1.append(4)
print(list1) # 输出为 [1, 2, 3, 4]
```
总的来说,extend方法可以添加多个元素,而append方法只能添加一个元素。如果要添加一个列表,可以使用extend方法;如果要添加一个单独的元素,可以使用append方法。