List Extend Method in Python

From this tutorial, you will be learning about Python list Extend method. You will see how to use it on sequences with the help of examples.

Note: The syntax used in the below section is for Python 3. You can change it to any other versions of Python.

Python List Extend

To Learn about Lists – Read Python List

List Extend Method

As we learned from previous tutorials, we can append elements to a list using the append method.

The append works fine when you want to add a single element or a list. But when you wish to append an individual letter from a word or an array of single-digit numbers, then it becomes impossible to achieve. Hence, the extend method got introduced to address this limitation.

This method updates the list by adding elements to the end. They can be a word or a number, etc. When you call this method, it traverses through the arguments and pushes them into the list one by one to the tail end.

Hence, the number of elements appended is the same as the number of arguments passed. It takes only one parameter and does not have a return value.

Its syntax is as follows:

List_name.extend(element)

After the extend method gets called, you will get the updated list object.

How does the Extend() function work?

When we pass the element to the extend method as an argument, it gets iterated, and the value from each iteration gets appended to the list.

The flowchart below attempts to explain it in a diagram:

Python List Extend Method Flowchart

List Extend Method Examples

While you use this method, consider the following points in mind.

a. When you add a “list” or “set” to a list, each element in the list gets iterated and appended to the tail end.

b. When you add a “string” to a list, the letters of the string get iterated and appended to the tail.

List to a List:

>>> myList = ["Lion", "Tiger", "Bear", "Cheetah", "Puma"]
>>> listToAdd = ["Leopard", "Lynx"]
>>> myList.extend(listToAdd)
>>> print(myList)
['Lion', 'Tiger', 'Bear', 'Cheetah', 'Puma', 'Leopard', 'Lynx']

Set to a List:

>>> myList = ['Physics', 'Chemistry', 'Biology', 'Electronics']
>>> setToAdd = {'Mathematics', 'Astrology'}
>>> type(setToAdd)
<class 'set'>
>>> myList.extend(setToAdd)
>>> print(myList)
['Physics', 'Chemistry', 'Biology', 'Electronics', 'Mathematics', 'Astrology']

String to a List:

>>> myList = ['X', 'Y', 'Z']
>>> myList.extend('abcd')
>>> print(myList)
['X', 'Y', 'Z', 'a', 'b', 'c', 'd']
>>>

Extend Method Time Complexity

It has a time complexity that is proportional to the length of the list that we want to add.

Best,

TechBeamers