The difference between the most commonly used extend method and append method in python

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 listis the list object to operate on and iterableis the iterable object to append.

Here are some extend()examples of how to use it:

  1. 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]
  1. 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']
  1. 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 listis the list object to operate on and elementis the element to append to the end of the list.

Here are some append()examples of how to use it:

  1. Append an element to the end of a list:
list1 = [1, 2, 3]
list1.append(4)
print(list1)  # 输出: [1, 2, 3, 4]
  1. Append a string as an element to a list:
list1 = ['a', 'b', 'c']
list1.append('d')
print(list1)  # 输出: ['a', 'b', 'c', 'd']
  1. 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 list2is appended to list1the end of as a whole, rather than list2appending 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.

Guess you like

Origin blog.csdn.net/m0_63007797/article/details/132154451