Python List Extend: Append Multiple Items to a List • datagy (2023)

In this tutorial, you’ll learn how to use the Python list extend method, which lets you append multiple items to a list. The Python .extend() method is very similar to the Python .append() method, but lets you add multiple elements to a list at once. You’ll learn how to use the Python extend method to add a single item or multiple items to a list, including from other lists, tuples, and more.

By the end of this tutorial, you’ll have learned:

  • How the Python list extend method works
  • How to add a single item or multiple items to a list using the extend method
  • How the method compares to different ways of adding items to a Python list
  • How the performance of different methods compares for larger lists

Table of Contents

Understanding the Python List extend Method

The Python extend() method takes all elements of another iterable (such as a list, tuple, string) and adds it to the end of a list. This gives it a key benefit over the .append() method, which can only append a single item to a list.

Let’s take a look at a few key characteristics of the Python .extend() method:

(Video) Python Collections Library deque - Intermediate Python Tutorial

  • The method takes an iterable as its parameter, such as a list, tuple or string
  • The method modifies the original list, but doesn’t return anything

Let’s explore the syntax of the Python list .extend() method:

# Understanding this Python list.extend() Methodlist.extend(iterable)

The operation takes place in place, meaning that you don’t need to re-assign the original list to itself. If you’re used to needing to re-assign items to themselves, this can take a little bit of time to get used to.

How to Append Multiple Items to a List with Python Extend

How can you append multiple items to a Python list?

The easiest way to add multiple items to a Python list is to use the .extend() method, which accepts a list of items and adds each item to the list. The operation happens in place, so you don’t need to reassign the list.

Now that you have an understanding of how the method works, let’s take a look at an example. We’ll start with two lists and append one to the other.

(Video) Python Collections Library Counter Counting Objects with Python

# Appending Multiple Items to a List with list.extend()list1 = [1,2,3]list2 = [4,5]list1.extend(list2)print(list1)# Returns: [1, 2, 3, 4, 5]

We can see that each item is added sequentially to the list that is being extended. The image below breaks this down a bit further:

Python List Extend: Append Multiple Items to a List • datagy (1)

We can see that each item in the list is added in the original order. As you’ll learn later using the .extend() method is the fastest way to add multiple items to a list.

Python List Extend with a Single Item

Now that you understand how the method works, let’s take a look at some oddities of the method. When we want to append a single item to our list using the .extend() method, we need to be careful about how we do this.

Let’s first take a look at how to add a single number to our list:

# Appending a Single Item to a List with .extend()list1 = [1,2,3]list1.extend(4)print(list1)# Raises: TypeError: 'int' object is not iterable

This raises a TypeError since the .extend() method expects an iterable object. In order to pass in a single item, we need to create it as a list, tuple, or another iterable type object. Let’s see how we can pass in a single item into the .extend() method:

# Appending a Single Item to a List with .extend()list1 = [1,2,3]list1.extend([4])print(list1)# Returns: [1, 2, 3, 4]

We can see by passing a list that contains only the single item the method works as expected.

Let’s now take a look at another example, where we have a list of strings. We can try and add another string to it using the .extend() method:

(Video) Python List Comprehensions | Python Tutorial | Why and How to Use Them | Learn Python Programming

# Adding a String to a List Using .extend()list1 = ['welcome', 'to']list1.extend('datagy')print(list1)# Returns# ['welcome', 'to', 'd', 'a', 't', 'a', 'g', 'y']

We can see that we didn’t really get what we wanted! While the method didn’t raise a TypeError, it appended each letter separately. This is because a string is iterable, meaning that Python interpreted that we wanted to iterate over the string and add each letter.

In order to add only the string as a single item, we need to pass it into a list or another iterable container:

# Adding a String to a List Using .extend()list1 = ['welcome', 'to']list1.extend(['datagy'])print(list1)# Returns# ['welcome', 'to', 'datagy']

In the following sections, you’ll learn about the difference between the Python .extend() method and other popular ways of adding items to a list.

Python List Extend vs Append

The Python list .append() method also adds to the back of a list. However, it only adds a single item. While the Python .extend() method failed when we attempted to add only a single item, the .append() method will work unexpectedly when we attempt to add a list of items.

Let’s see how these two methods compare:

# Comparing List .extend() vs .append()list1_append = [1,2,3]list1_extend = [1,2,3]list2 = [4,5,6]list1_append.append(list2)list1_extend.extend(list2)print(f'{list1_append=}')print(f'{list1_extend=}')# Returns:# list1_append=[1, 2, 3, [4, 5, 6]]# list1_extend=[1, 2, 3, 4, 5, 6]

We can see that by trying to add multiple items to a list using .append(), that all the items are added as a single list.

In order to be able to append each item separately using the .append() method, we would need to use a for loop:

(Video) Pandas Merge Function | Python Pandas Tutorial #9 | Merge dataframes in Pandas, SQL-Joins in Pandas

# Adding Multiple Items with .append()list1_append = [1,2,3]list2 = [4,5,6]for item in list2: list1_append.append(item)print(list1_append)# Returns: [1, 2, 3, 4, 5, 6]

Python List Extend vs the Plus (+) Operator

Another common way to add items to the end of a list in Python is to use the + operator. This method concatenates the two lists. Because the operation doesn’t happen place, it creates a new object that combines the two lists.

Let’s take a look at an example of how this works:

# Adding Items to a List with +list1 = [1,2,3]list2 = [4,5,6]list1 = list1+list2# Returns: [1, 2, 3, 4, 5, 6]

We can also abbreviate this using the augmented assignment operator to the following:

# Using the Augmented Assignment Operator to Concatenate Listslist1 = [1,2,3]list2 = [4,5,6]list1 += list2# Returns: [1, 2, 3, 4, 5, 6]

In the next section, we’ll take a look at the performance of these different methods.

Performance Comparisons of Adding Items to a List in Python

We can time the execution time of different methods by using Jupyter Notebooks and the %%timeit command. The table below breaks down the different methods and their run times when attempting at concatenate a list of one million items to it:

MethodPerformance Run Time
.extend()20.4 ms ± 502 µs per loop
.append()52.5 ms ± 466 µs per loop
+1min 21s ± 4.19 s per loop

We can see that the .extend() method is the clear winner, while using the .append() method is a near second. Meanwhile, using the + method is the worst performing of all them for larger lists.

Conclusion

In this tutorial, you learned how to use the Python .extend() method to add multiple items to a list. You learned how the method works and how it can be used to extend lists using other iterable objects. You learned some of the quirks of using this method, such as when adding single items to the list.

(Video) Python Map Function

You then learned how the .extend() method compares to other ways of adding items to the end of a list, including the .append() method and using the + operator. Finally, we explored the performance of different methods, indicating that when working with large lists that the .extend() method is the clear winner.

Additional Resources

To learn more about related topics, check out the articles below:

  • Python Lists: A Complete Overview
  • Python: Combine Lists – Merge Lists (8 Ways)
  • How to Append to Lists in Python – 4 Easy Methods!
  • Prepend to a Python a List (Append at beginning)

Videos

1. Pandas Group By | Python Pandas Tutorial #4 | Split Apply Combine | Python Pandas Aggregate Date
(datagy)
2. Automate Excel Reporting with Python! Combine Workbooks and Add Charts with Pandas and Openpyxl
(datagy)
3. Python Excel Automation #1 - Consolidate Excel Workbooks, Python Pivot Tables, and Excel Charts
(datagy)
4. Python Pivot Tables Tutorial | Create Pandas Pivot Tables | Python Tutorial | Examples, Subtotals
(datagy)
5. Pandas Conditional Columns: Set Pandas Conditional Column Based on Values of Another Column
(datagy)
6. Style Python Pandas DataFrames! (Conditional Formatting, Color Bars and more!)
(datagy)
Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated: 01/01/2023

Views: 5555

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.