append() and extend() in Python

20-04-23 Ahmed Obaid 4976 0

​In this article, we will explain the append() and extend() functions, and explain the functions that each performs and the difference between them.

append() function

The append() function in Python adds one item to a list. The element is added to the end of the original list instead of returning a new list. Adds the argument as a single element at the end of the list. List length increases by only one item.


How to formulate it like this:

list. append(object)

Parameters:

Object: (Required) The item to be added to the specified list.

Return value: The append() function does not return any value, but updates the original list with the specified element added to the end.


Example:

list = ["python", "java", "php"] # The original list
list.append("django")#Add a specified element or object to the parent list
print(list)

The output will be:

['python', 'java', 'php', 'django']

Append a list to another list using the append() function

List is an object. If you append a list to another list, the append() function will add the other list at the end of the original list.undefined .

 Example:

 list = ["1", "2", "3"] # The original list
 another_list = ["4", "5", "6"] # Another list to be added
 list. append(another_list)
 print(list)

 The output will be:

 ['1', '2', '3', ['4', '5', '6']]

 Note: You should keep in mind that the append() function only adds one element at a time.

 Note: You can add multiple elements using the append() function by using loops.

 extend() function

 The extend() function expands the list by appending all iterable elements directly to the original list. Iterator can be a list or a collection.


 How to formulate it like this:

list. extend(iterable)

 Parameters:

 Iterable: (Required) Items that are iterable. Items to be appended to the selected list.

 Return value: The extend() function does not return any value, but modifies the original list.


 Example:

list = ["1", "2", "3"] # The original list
 another_list = ["4", "5", "6"] # the other list whose items you want to include in the list undefined The original
 list. extend(another_list)
 print(list)

 The output will be:

 ['1', '2', '3', '4', '5', '6']

 External sources:

 Lists - The official Python documentation

 If you have any questions or concerns, leave them in the comment



Tags


Python python data types python lists append() and extend() in Python

Share page