You might have used extend method in Lists where it can be used to add multiple elements to a list object. But what else it can be do is the topic of our discussion here.
To add multiple elements to a list using extend method is technically not a right way of understanding the method functionality. Because it can do multiple things. Lets see the various features of it.
The syntax of extend method looks like below. It says the method can accept any iterable. Now the question is what is an Iterable.
extend(self, iterable, /) Extend list by appending elements from the iterable.
Any object that can be iterated upon is called an Iterable. Some of the iterables in python most often we encounter are lists, dictionaries, sets, tuples, generator expressions, generator functions etc.
Following is the usage of how to use the extend method in various ways. In the below examples we were able to add a list, tuple, set or dictionaries to a list object.
Not only simple data types we can also use generator expression results to add to a list object using extend method. Below is an example where it is adding multiples of 20 from 1000 to 1100 generator by a generator expression.
Following is a generator function which generates a list of prime numbers upto a given number. The same also can be used in extend method.