Home Icon Home Resource Centre Python extend() Function | Syntax, Techniques & More (+Examples)

Table of content: 

  • What Is Extend In Python?
  • Extend In Python With List
  • Extend In Python With String
  • Extend In Python With Tuple
  • Extend In Python With Set
  • Extend In Python With Dictionary
  • Other Methods To Extend A List In Python
  • Difference Between append() and extend() In Python
  • Conclusion
  • Frequently Asked Questions
expand icon

Python extend() Function | Syntax, Techniques & More (+Examples)

In Python, extend() is a list method that adds elements from an iterable (like a list, tuple, or set) to the end of the existing list. It modifies the original list in place and returns None.
Schedule Icon 0 min read
Python extend() Function | Syntax, Techniques & More (+Examples)

In Python, the extend() function is a built-in method that belongs to list objects. It is used to add all elements of an iterable (such as a list, tuple, or set) to the end of an existing list. Unlike the append() method, which adds a single element to the list, extend() enables you to concatenate multiple elements at once, making it an essential tool for list manipulation and data aggregation.

In this article, we will explore the extend() function in detail, covering its syntax, how it operates with different iterable types, and practical use cases. We will also provide examples to illustrate its functionality, compare it with similar methods, and discuss best practices for using extend() effectively.

What Is Extend In Python?

Extend a list in Python

The extend() method in Python programming is used to add elements from an iterable to the end of a list. This method allows you to combine lists or add multiple items at once. It is important to understand how this method works for effective list management.

Syntax Of Extend In Python

The syntax for using extend() in Python is straightforward:

list.extend(iterable)

Here:

  • list: This is the target list that will be modified.
  • iterable: This can be any iterable object, such as a list, tuple, or string. Each element of this iterable will be added to the list.

Return Value Of Extend In Python

The extend() function in Python does not return a new list i.e. it returns None. Instead, it modifies the original list in place:

  • It iterates over each element in the provided iterable.
  • Each element is added one by one to the end of the existing list.

We will now look at some common code examples to understand how to work with extend() method in Python programming.

Extend In Python With List

The extend() method can be used to merge one list into another by appending all elements of the second list to the first. This is useful for combining lists without creating a new list, allowing for efficient data management.

Code Example:

Output:

[10, 20, 30, 40, 50, 60]

Explanation:

In the above code example-

  1. We start by initializing two lists, list1 containing the values [10, 20, 30] and list2 containing the values [40, 50, 60].
  2. Next, we use the extend() method on list1 to add all the elements from list2 to it. This method modifies list1 in place, meaning it will now contain both its original elements and the elements from list2.
  3. Finally, we print the modified list1 to see the result. The output shows that the elements from list2 have been successfully added to list1.
Explore this amazing course and master all the key concepts of Python programming effortlessly!

Extend In Python With String

Python allows us to extend lists with strings. This is useful when you want to add multiple characters or words into a list. When a string is used with extend(), each character of the string is treated as a separate element, allowing for easy concatenation of characters to a list.

Code Example:

Output:

['A', 'B', 'C', 'D', 'E', 'F']

Explanation:

In the above code example-

  1. We start by initializing a list, list1, with the values ['A', 'B', 'C'], and a string, string1, containing the characters 'DEF'.
  2. Next, we use the extend() method on list1 to add the characters from string1. Each character of the string is added individually to the list.
  3. Finally, we print the modified list1 to see the result. The output showcases that the characters from string1 have been successfully appended to list1.

Extend In Python With Tuple

Tuples are a type of data structure in Python. They hold a collection of items. Unlike lists, tuples are immutable, meaning their contents cannot be changed after creation. This characteristic makes them useful for storing fixed collections of data.

The extend() method is typically used with lists. However, you can still use it with tuples by converting them to lists first. This approach allows you to add items from a tuple to a list effectively.

Code Example:

Output:

[7, 8, 9, 10, 11, 12]

Explanation:

In the above Python code example-

  1. We begin by initializing a list, list1, with the values [7, 8, 9], and a tuple, tuple1, containing the values (10, 11, 12).
  2. Next, we use the extend() method on list1 to add the elements from tuple1. During this process, the tuple is automatically converted to a list, enabling us to append its elements to list1.
  3. Finally, we print the modified list1 to see the result. The output confirms that the elements from tuple1 have been successfully added to list1.

Extend In Python With Set

The extend() method cannot be directly used with sets because it is specifically designed for lists. However, we can convert a set to a list and then use extend() to add its elements to another list. This approach allows us to effectively merge elements from a set into a list.

Code Example:

Output:

[1, 2, 3, 4, 5, 6]

Explanation:

In the above code example-

  1. We start by initializing a list, list1, with the values [1, 2, 3], and a set, set1, containing the values {4, 5, 6}.
  2. Next, we use the extend() method on list1 to add the elements from set1. During this process, the set is automatically converted to a list, allowing us to append its elements to list1.
  3. Finally, we print the modified list1 to see the result. The output indicates that the elements from set1 have been successfully added to list1.

Extend In Python With Dictionary

Dictionaries in Python are collections of key-value pairs. Each key is unique, and it maps to a specific value. We can extend a list with the keys or values of a dictionary. When using extend(), we can choose to add either the keys or the values, depending on your requirements.

Code Example:

Output:

['X', 'Y', 'Z', 'a', 'b', 'c']

Explanation:

In the above Python code example-

  1. We start by initializing a list, list1, with the values ['X', 'Y', 'Z'], and a dictionary, dict1, containing the key-value pairs {'a': 1, 'b': 2, 'c': 3}.
  2. Next, we use the extend() method on list1 to add the keys from dict1. This adds each key from the dictionary to the list.
  3. Finally, we print the modified list1 to see the result. The output indicates that the keys from dict1 have been successfully appended to list1.
Sharpen your coding skills with Unstop's 100-Day Coding Sprint and compete now for a top spot on the leaderboard!

Other Methods To Extend A List In Python

In addition to the extend() method, there are several other ways to extend a list in Python. Here, we’ll explore three alternative methods: using the + operator, slicing syntax, and the chain() method from the itertools module.

Using The + Operator

The + operator, also known as the concatenation operator, can be used to concatenate two lists, creating a new list that combines both. This method does not modify the original list but returns a new one.

Code Example

Output:

[1, 2, 3, 4, 5, 6]

Explanation:

In the above Python code example-

  1. We start by initializing two lists: list1 with the values [1, 2, 3] and list2 with the values [4, 5, 6].
  2. Next, we use the + operator to combine the two lists, which creates a new list named result.
  3. This operation does not modify the original lists; instead, it produces a new list that contains the elements of both list1 and list2.
  4. Finally, we print the new combined list, result, to see the outcome. The output shows that the elements from both lists have been successfully combined into one list.

Using Slicing Syntax

Slicing syntax is another way to extend a list. This method involves using the slice assignment feature of Python. Slicing can insert elements from another list into a specific position within the original list. It allows for more control over where the elements are added.

Code Example:

Output:

[7, 8, 9, 10, 11, 12]

Explanation:

In the above code example-

  1. We start by initializing a list, list1, with the values [7, 8, 9] and another list, list2, containing the values [10, 11, 12].
  2. Next, we use slicing to extend list1 with the elements from list2. Specifically, we set the slice list1[len(list1):] to list2, which effectively adds the elements of list2 to the end of list1.
  3. Finally, we print the modified list1 to see the result. The output indicates that the elements from list2 have been successfully added to the end of list1.

Using The chain() Method

The chain() method from the itertools module can combine multiple tables into a single iterable. This method is especially useful for combining various types of tables, such as lists, tuples, and sets. It avoids creating intermediate lists and is generally more efficient in terms of memory usage.

Code Example:

Output:

[13, 14, 15, 16, 17, 18]

Explanation:

In the above code example-

  1. We begin by importing the chain() function from the itertools module.
  2. Next, we initialize a list, list1, with the values [13, 14, 15], and a tuple, tuple1, containing the values (16, 17, 18).
  3. We then use the function chain() function to combine list1 and tuple1. The chain() function takes multiple iterable inputs and produces a single iterable that yields elements from each input in sequence.
  4. We convert the result of chain() to a list, storing it in the variable result.
  5. Finally, we print the new combined list, result, to see the outcome. The output confirms that the elements from both list1 and tuple1 have been successfully combined into one list.

Difference Between append() and extend() In Python

Given below are the key differences between the append() and extend() method in Python:

Feature append() extend()
Purpose Adds a single element to the end of the list. Adds multiple elements from an iterable to the end of the list.
Parameter Type Accepts a single element (any data type). Accepts an iterable (like a list, tuple, or set).
Return Value Returns None. Returns None.
Modification Modifies the original list by adding one element. Modifies the original list by adding multiple elements.
Usage Example list.append(item) list.extend(iterable)

Code Example:

Output:

[1, 2, 3, 4, 5, 6, 7]

Explanation:

In the above code example-

  1. We start by initializing a list called my_list with the values [1, 2, 3].
  2. Next, we use the append() method to add a single element, 4, to the end of my_list. After this operation, the list becomes [1, 2, 3, 4].
  3. Then, we use the extend() method to add multiple elements at once. We pass the list [5, 6, 7] to extend(), which adds these elements to the end of my_list.
  4. Finally, we print the modified my_list to see the result. The output will be [1, 2, 3, 4, 5, 6, 7], confirming that both the single element and the multiple elements have been successfully added to the list.
Searching for someone to answer your programming-related queries? Find the perfect mentor here.

Conclusion

The extend() method in Python language is a powerful tool for efficiently adding multiple elements from an iterable to the end of a list. By understanding its syntax, return value, and usage with various data types such as lists, sets, tuples, strings, and dictionaries, you can enhance your list manipulation capabilities.

We also explored alternative methods for extending lists, including the + operator, slicing syntax, and the chain() method from the itertools module. Each offers unique advantages depending on the context. By mastering these techniques, you can choose the most suitable approach for your specific programming needs, leading to cleaner and more effective code.

Frequently Asked Questions

Q. What is Python List extend() method?

The Python extend() method is a built-in function used to add multiple elements from an iterable (such as a list, tuple, set, or string) to the end of an existing list. Unlike append(), which adds a single element as a whole to the list, extend() iterates over the given iterable and adds each element individually to the list.

Key Points:

  • Modifies the list in place: The original list is updated directly.
  • Takes an iterable: You can pass any iterable (e.g., list, tuple, set, string) to extend(), and each element from the iterable is added to the list.
  • No return value: It modifies the list but does not return a new list or any value (None is returned).

Q. Can I use the extend() method to add non-iterable elements like integers to a list?

No, the extend() method only works with iterables, such as lists, tuples, sets, strings, and dictionaries (keys or values). If you try to pass a non-iterable like an integer, Python will raise a TypeError. If you want to add a single non-iterable element (such as an integer), you should use the append() method instead. For Example-

my_list = [1, 2, 3]
my_list.extend(4) # Raises TypeError
# Use append() instead
my_list.append(4)

Q. Does the extend() method return a new list or modify the existing one?

The extend() method modifies the existing list in place and does not return a new list. After using extend in Python, the original list will be updated with the new elements. If you need a new list with the combined elements, you can use the + operator or create a copy of the original list before extending it.

Q. How is extend() different from using the + operator to concatenate lists?

The key difference is that extend() modifies the list in place, while the + operator creates a new list that combines the two. If you want to keep the original list unchanged and create a new list with the combined elements, the + operator is the better option. If you want to update the original list, use extend(). For Example-

Q. What happens if I extend a list with an empty iterable?

If you extend a list with an empty iterable, such as an empty list [] or an empty tuple (), the original list remains unchanged. The extend() method only adds elements from the iterable, so if the iterable is empty, no elements are added. For Example-

In these cases, the extend() method does nothing because there are no elements to add.

Q. Can I use extend() to combine more than two lists or iterables at once?

No, the extend() method can only take one iterable at a time. If you want to combine more than two lists or iterables, you can call extend() function multiple times or use other methods like the + operator or itertools.chain() to handle multiple iterables simultaneously.

With this, we conclude our discussion on the extend() function in Python. Here are a few other topics that you might be interested in reading:

  1. Difference Between C and Python | C or Python - Which One Is Better?
  2. 10 best Python IDE to develop world-class software and application
  3. Difference Between Java And Python Decoded
  4. 10 Important Features Of Python That You Must Know!
  5. Best Python Books For Beginners, Intermediates And Experts
Edited by
Muskaan Mishra
Technical Content Editor

I’m a Computer Science graduate with a knack for creative ventures. Through content at Unstop, I am trying to simplify complex tech concepts and make them fun. When I’m not decoding tech jargon, you’ll find me indulging in great food and then burning it out at the gym.

Tags:
Python programming language

Comments

Add comment
No comments Image No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.