Table of Contents
Python List Extend
To Learn about Lists – Read Python List
List Extend Python
As we realized from earlier tutorials, we are able to append parts to an inventory utilizing the append technique.
The append works positive once you need to add a single component or an inventory. But once you want to append a person letter from a phrase or an array of single-digit numbers, then it turns into not possible to obtain. Hence, the lengthen technique bought launched to handle this limitation.
This technique updates the listing by including parts to the tip. They is usually a phrase or a quantity, and so forth. When you name this technique, it traverses by the arguments and pushes them into the listing one after the other to the tail finish.
Hence, the variety of parts appended is the identical as the variety of arguments handed. It takes just one parameter and does not have a return worth.
Its syntax is as follows:
After the lengthen technique will get known as, you’ll get the up to date listing object.
How does the Extend() perform work?
When we pass the component to the lengthen technique as an argument, it will get iterated, and the worth from every iteration will get appended to the listing.
The flowchart beneath makes an attempt to clarify it in a diagram:
List Extend python Method Examples
While you utilize this technique, contemplate the next factors in thoughts.
a. When you add a “list” or “set” to an inventory, every component in the listing will get iterated and appended to the tail finish.
b. When you add a “string” to an inventory, the letters of the string get iterated and appended to the tail.
List to a List:
>>> myList = ["Lion", "Tiger", "Bear", "Cheetah", "Puma"] >>> listingToAdd = ["Leopard", "Lynx"] >>> myList.lengthen(listingToAdd) >>> print(myList) ['Lion', 'Tiger', 'Bear', 'Cheetah', 'Puma', 'Leopard', 'Lynx']
Set to a List:
>>> myList = ['Physics', 'Chemistry', 'Biology', 'Electronics'] >>> setToAdd = 'Mathematics', 'Astrology' >>> kind(setToAdd) <class 'set'> >>> myList.lengthen(setToAdd) >>> print(myList) ['Physics', 'Chemistry', 'Biology', 'Electronics', 'Mathematics', 'Astrology']
String to a List:
>>> myList = ['X', 'Y', 'Z'] >>> myList.lengthen('abcd') >>> print(myList) ['X', 'Y', 'Z', 'a', 'b', 'c', 'd'] >>>
Extend Method Time Complexity
It has a time complexity that is proportional to the size of the listing that we wish to add.