What will be the output after the following statements?
x= [5, 4, 3, 2, 1]
y=[0.5, 10]
x.extend(y)
print(x)
0 (, ,
(a) (5, 4, 3, 2, 1, 0, 5, 10)
O (b)
O (c) (5, 4, 3, 2, 1]
O (d) [0, 5, 10, 5, 4, 3, 2, 1]
Answers
The output will be [5, 4, 3, 2, 1, 0.5, 10]
Explanation:
The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list.
The output will be [5, 4, 3, 2, 1, 0, 5, 10]
Let's write the full question
What will be the output after the following statements?
x= [5, 4, 3, 2, 1]
y = [0, 5, 10]
x.extend(y)
print(x)
(a) (5, 4, 3, 2, 1, 0, 5, 10)
(b) [5, 4, 3, 2, 1, 0, 5, 10]
(c) (5, 4, 3, 2, 1]
(d) [0, 5, 10, 5, 4, 3, 2, 1]
(b) [5, 4, 3, 2, 1, 0, 5, 10] is the correct answer.
Extra Information
append() method in Python takes the argument and adds it as a single element at the end of the list.
extend() method in Python loops over the argument which helps us in adding each element in the list.
Example
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
Here our argument is b = [6, 7, 8, 9]
A) a.append(b)
If this is used then the output will be
a = [1, 2, 3, 4, 5, [6, 7, 8, 9]]
B) a.extend(b)
If this is used then the output will be
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Python was created by Guido van Rossum and came into existence in 1991. It is a high-level and general programming language. It is a very lucid programming language as it has a good language construct and object-oriented approach. It is dynamically typed and garbage-collected.