Python extend() function is used to adds the specified list elements (or any iterable) to the end of the current list. In simple words can say extend() method appends the contents of seq to list.
Note: Python list extends returns none, only modifies (Add new elements) the original list.
Required a single argument (a list) and adds it to the end.
It doesn’t return any value, only modifies the original list.
Python list extend examples
We will do some simple examples and with different types of Iterable like- List, tuple, set, etc.
Adding all items of a list
Add the elements of programming to the language list:
# language list language = ['French', 'English', 'German'] # another list of programing language programing = ['python', 'Java'] language.extend(programing) print('Extended List: ', language)
Add Elements of Tuple List
# language list language = ['French', 'English', 'German'] # language tuple language_tuple = ('Spanish', 'Portuguese') # appending element of language tuple language.extend(language_tuple) print('New Language List: ', language)
New Language List: [‘French’, ‘English’, ‘German’, ‘Spanish’, ‘Portuguese’]
Add Elements of Tuple List
Example of Add a tuple to the list of the fruits.
fruits = ['apple', 'banana', 'cherry'] points = (1, 3, 5, 7) fruits.extend(points) print(fruits)
[‘apple’, ‘banana’, ‘cherry’, 1, 3, 5, 7]
Possible to Python extend multiple lists?
Yes, it is Possible to append multiple lists at once in python.
x += y+z
x = x+y+z
Python list extend vs +
The only difference on a bytecode level is that the
.extend the way involves a function call, which is slightly more expensive in Python than the
It will not affect unless performing this operation billions of times. It is likely, however, that the bottleneck would lie someplace else.
Q: What is the Difference between append and extend in python?
Answer: Function append and extend in python are:-
append: Appends object at the end.
x = [1, 2, 3] x.append([4, 5]) print (x)
[1, 2, 3, [4, 5]]
extend: Extends list by appending elements from the iterable.
x = [1, 2, 3] x.extend([4, 5]) print (x)
[1, 2, 3, 4, 5]
Q: How to add lists using + or += operator?
Answer: Example of add items of a list to another list using + or += operator.
a = ["A", "B"] b = [3, 4] print(a + b)
Output: [‘A’, ‘B’, 3, 4]
Do comment if you have any queries and suggestions on the method list extend Python 3.
IDE: PyCharm 2020.1.1 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.