Difference between append and extend list in Python
Question
Python list data structure has append() and extend() methods. Both methods add new items to the list. What is the difference between the two?
Append vs extend list in Python
- Append: adds a new item to the end of the list. The item can be an object of any type. It could be a number, a string, a list, etc
- Extend: takes an iterable object as input, iterate through all elements and append them all one by one to the end of the list
What is an iterable?
Iterable examples include (list, tuple, string, etc). Fore more information about iterators, iterables and generators, you may check the following post.
Append extend example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
A = [1, 2, 3] print(A) A.append([4, 5]) print(A) A.extend([6, 7]) print(A) A.append('ABC') print(A) A.extend('ABC') print(A) |
If you run the code snippet above, you will get the following output:
1 2 3 4 5 |
[1, 2, 3] [1, 2, 3, [4, 5]] [1, 2, 3, [4, 5], 6, 7] [1, 2, 3, [4, 5], 6, 7, 'ABC'] [1, 2, 3, [4, 5], 6, 7, 'ABC', 'A', 'B', 'C'] |
What is the big deal about using extend ? can not we just use append multiple times ? Yes we can but using extend is more efficient. I have not researched why is believed to be faster. Let me know in the comments section if you know the reasoning? At least, using extend instead of multiple appends makes the code more elegant.
Summary
That is for today. Let us summarize…
When to use |
---|
Use append() if you want to add an element at the end of a list |
Use extend() if you want to combine another iterable elements to the list |
References
Thanks for reading. Please use the comments section below for questions and feedback.