The append() and extend() methods are both used to add elements to a list in Python. However, they have different behaviors.
The append() method adds a single element to the end of a list. The length of the list itself will increase by one. For example, the following code will add the element
4 to the end of the list list1:
Python
list1 = [1, 2, 3]
list1.append(4)
print(list1)
The output of the code is:
Code snippet
[1, 2, 3, 4]
The extend() method iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument. For example, the following code will add the elements
5 and 6 to the end of the list list1:
Here is a table summarizing the differences between append() and
extend():
Feature
append()
extend()
Adds a single element
Yes
No
Adds elements from an iterable
No
Yes
Increases the list length by one
Yes
Length of iterable
Time complexity
O(1)
O(k)
Here are some examples of how append() and extend() can be used:
Python
# Append a single element to a list
list1 = [1, 2, 3]
list1.append(4)
print(list1)
# Extend a list with the elements of another list
list2 = [5, 6]
list1.extend(list2)
print(list1)
# Extend a list with the elements of a string
list1 = [1, 2, 3]
list1.extend("abc")
print(list1)
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The
append()andextend()methods are both used to add elements to a list in Python. However, they have different behaviors.The
append()method adds a single element to the end of a list. The length of the list itself will increase by one. For example, the following code will add the element4to the end of the listlist1:Python
The output of the code is:
Code snippet
The
extend()method iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument. For example, the following code will add the elements5and6to the end of the listlist1:Python
The output of the code is:
Code snippet
Here is a table summarizing the differences between
append()andextend():append()extend()Here are some examples of how
append()andextend()can be used:Python