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

If you run the code snippet above, you will get the following output:

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.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *