Difference Between append() and extend() in Python

Difference Between append() and extend() in Python

When you plan to build an application in Python, operating with lists becomes a common Working with lists is a common task in Python, and two frequently used methods for adding elements to a list are append() and extend(). The append() method adds a single item to the end of a list, while extend() adds multiple items from another list or iterable. Though they seem similar, they behave differently and are used in different situations. In this blog, you will understand what the append and extend methods in Python are, along with their key differences and examples for each.

Table of Contents:

What is the append() Method in Python?

The append() method in Python is used to add a single element at a time to the end of an existing list. The method does not modify existing elements; instead, it adds an item to the list as a single element.

append() Method in Python

Syntax:

list.append(item)

Example:

Python

Output:

 append() Method in Python

Explanation: Here, 4 is considered as one complete element that gets added at the end of the number list. The previous list had three items, and now it has four items because another one was added because of the append() method.

Example 2: append() with strings

Python

Output:

append() with strings

Explanation: In this case, append() added the entire string “Machine Learning” as a single element at the end of the list.

What is the extend() Method in Python?

The extend() method serves a different purpose in Python. It is used in cases where you want to add several elements from another iterable, which could be a list, a tuple, or a set, to the end of the existing list, one at a time.

extend() Method in Python

Syntax: 

list.extend(iterable)

Example:

Python

Output:

extend() Method in Python

Explanation: Here, instead of adding the whole list [‘d’, ‘e’] as a single element, the extend() method doesn’t add the list as a single element, instead, it unpacks the list to add each item to the list of numbers individually. This proves useful when you want to merge multiple items from an iterable into your list.

Example 2: extend() with a string

Python

Output:

extend() with a string

Explanation: Here, since “ML” is a string (an iterable), extend() split it into ‘M’ and ‘L’ and added each character separately to the list.

Comparison Table Between append() and extend() in Python

Featureappend()extend()
BehaviorAdds a single element to the list.Adds each element from an iterable to the list.
Changes the list length by1 (one new item regardless of type).By the number of items in the iterable.
Can it flatten another list?No, it nests the list as a single item.Yes, it inserts the elements individually.
Accepts IterablesYes, but it treats it as a single object.Yes, and unpacks its contents into the list.
Common use caseAdd one object or result to a list (e.g., a new log entry).Merge two lists or append multiple elements at once.

Summary of Differences Between append() and extend() 

Here, we will give you the essential differences. The Method append() adds one item (whatever the item is) to the end of the list, while extend() takes an iterable and adds each of the elements that are to be added to the list. With append(), even if you give it a list, it will add it as one nested element, while with extend(), you can flatten the incoming iterable into your original list.

Performance Implications of extend() vs append()

Using extend() inside a loop to add multiple elements is more efficient than using append() repeatedly. When you use append(), each item is added one by one, which can be slow and use more memory, especially for large lists. But with extend(), all the items from another list or iterable are added in one go, making it faster and more memory-efficient. So, extend() is the better choice when you need to add many elements at once.

We will demonstrate this by using the Python time module.

For Example:

Python

Output:

Performance Implications of extend() vs append

Explanation: Here, extend() works significantly faster than using append() in a loop for adding many items. This is because extend() is implemented in C under the hood, meaning its logic is written in C, and it greatly optimizes memory allocation during the operation. On the other hand, append() repeatedly incurs an extra overhead on each case of iteration.

Best Practices When Using append() and extend()

Go through the following tips to avoid bugs and ensure that you utilise the methods to their full potential:

  • When adding a single item, use append(): it is good practice to use append(), as extend() will be an inefficient method with less clarity when it comes to adding one item to the list.
  • When merging lists or any iterables, use extend(): You can avoid unnecessary nesting and make your output more readable.
  • Avoid Unintended List Nesting: If you don’t want to get confused while writing the code, it’s better not to use nested loops for lists or nest lists inside one another. This can occur when you accidentally use append() with another list, which can lead to structures like [[‘a’, ‘b’], ‘c’].
  • Always confirm the type of object you’re adding: You can avoid TypeError by passing your iterable to extend() and not an integer value or float.
  • You should be explicit in your intentions: You can keep a habit of commenting your code when it is not immediately obvious why you are choosing append() or extend().

Real-World Use Cases for append() and extend() in Python

The section below will implement use cases for both methods, further expanding your capabilities to operate with them.

1. Logging into a site: Tracking individual user actions as they occur.

Example: 

Python

Output:

Logging into a site

Explanation: In the example above, each action done by the user is added as an individual log message. Now, since the user is recording one event at a time as a whole string, our best method to implement is append().

2. Comparing courses in a list: Combining multiple course details into one list for comparison.

Example: 

Python

Output:

Comparing courses in a list

Explanation: Here, you’re combining two lists. Using extend() unpacks the second list, which is new_products, and adds each item to the first list, which is main_products, individually. When you want to consolidate data from multiple sources, this case is useful.

Conclusion

When working with lists in Python, it’s important to know the difference between append() and extend(). If you want to add just one item to the list, use append(). But if you want to add multiple items from another list or group, use extend(). Understanding these differences will help you write clearer and better code. By following the right practices, you can avoid mistakes and make your list operations easier to understand.

Further, check out the Python certification course and get ready to excel in your career with Basic Python interview questions prepared by experts.

 

The tutorials listed here emphasize Python’s primary data structures such as lists, dictionaries, and tuples.

itertools in Python – This essential guide helps you master the use of itertools in Python.
Check Key in Dictionary – A comprehensive resource designed to help you excel at checking keys in dictionaries in Python.
Sort Dictionary by Value – Your go-to reference for mastering how to sort dictionaries by value in Python.
Add New Keys to Dictionary – An invaluable resource for learning how to add new keys to dictionaries effectively in Python.
Check if List is Empty – A key guide for understanding how to check if a list is empty in Python.
Count Occurrences in List – The ultimate resource to master counting occurrences in lists using Python.
Remove Element by Index – An important read for learning how to remove elements by index in Python lists.
Find Index in List – A detailed resource for mastering the process of finding indexes in Python lists.
Concatenate Lists – An indispensable guide for mastering list concatenation techniques in Python.

Difference Between Append and Extend – FAQs

Q1. Can I use append() with a dictionary or a tuple?

Yes, append() accepts any data type; It will treat the whole object as one item and add it to the end.

Q2. What happens if I extend() a list with a string?

Each character of the string is added as a separate element. So we need to be cautious of that.

Q3. Is extend() faster than multiple append() calls?

Yes, especially when you’re adding a large number of items. extend() is optimized for bulk additions.

Q4. Can I chain append() or extend() calls?

No, both methods return None. If you try to chain them, you’ll get an error.

Q5. What if I append() an empty iterable?

You’ll just get an empty iterable as a nested element, for example, [0, 1, 2].

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner