The list
is the most flexible data type in Python, it represents a collection of ordered elements. Lists are mutable meaning that operations such as insertions and deletions can be performed on them in-place i.e without necessarily creating a new a list.
The extend()
method is used to add elements from another iterable to the end of the list. It offers a far more convenient approach compared to manually looping through the iterable and appending a single element to the list during each iteration.
The syntax of the extend() method is as shown below:
lst.extend(iterable)
copy
iterable |
The iterable object containing the elements to be added at the end of the list |
The function adds all the elements of the iterable at the back of the list and returns None
.
In the above example, we used a range as the iterable argument.
In the above example we called the extend method of the first list i.e 'mylist
' with the second list i.e 'another_list
' as the argument. The outcome is that all the elements of 'another_list' are appended at the end of 'mylist
' while 'another_list
' remains unchanged.
In the above example we used a set as the argument to the extend()
method of the list. Elements in a set have no order so the way they are added in the list may be unpredictable.
extend() vs append() methods
Lists also includes the append()
method which can also be used to add an element at the end of the list. However, the append()
method can only add a single element while as we have seen, the extend()
method adds multiple elements at once.