1. The extend method
In Python, extend()
a method of a list object that appends the elements of an iterable (usually another list) to the end of the current list. This method modifies the original list without creating a new one.
extend()
The syntax of the method is as follows:
list.extend(iterable)
where list
is the list object to operate on and iterable
is the iterable object to append.
Here are some extend()
examples of how to use it:
- Append one list to the end of another:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # 输出: [1, 2, 3, 4, 5, 6]
- Append each character of a string to a list:
list1 = ['a', 'b', 'c']
string = 'def'
list1.extend(string)
print(list1) # 输出: ['a', 'b', 'c', 'd', 'e', 'f']
- Append the elements of an iterator object to the list:
list1 = ['a', 'b', 'c']
iterable = ('x', 'y', 'z')
list1.extend(iterable)
print(list1) # 输出: ['a', 'b', 'c', 'x', 'y', 'z']
Note that, extend()
unlike methods, append()
methods add the entire iterable as one element to the end of the list. Therefore, use extend()
method to append the elements of the iterable to the list one by one, instead of appending the entire iterable as a single element.
Two, append method
In Python, append()
a method of the list object that appends an element to the end of the current list. Unlike extend()
methods, append()
methods do not split elements into separate items when appending them.
append()
The syntax of the method is as follows:
list.append(element)
where list
is the list object to operate on and element
is the element to append to the end of the list.
Here are some append()
examples of how to use it:
- Append an element to the end of a list:
list1 = [1, 2, 3]
list1.append(4)
print(list1) # 输出: [1, 2, 3, 4]
- Append a string as an element to a list:
list1 = ['a', 'b', 'c']
list1.append('d')
print(list1) # 输出: ['a', 'b', 'c', 'd']
- Append a list as an element to the end of the list:
list1 = ['a', 'b', 'c']
list2 = ['x', 'y', 'z']
list1.append(list2)
print(list1) # 输出: ['a', 'b', 'c', ['x', 'y', 'z']]
Note that this list2
is appended to list1
the end of as a whole, rather than list2
appending the elements in individually.
append()
method adds a new element to the end of the list as a whole, whereas extend()
method adds elements from an iterable object to the list one by one. You can choose to use one of them according to your specific needs.