What is the output for the following code?
alpha = [21,32,12,1,2,7,55]
alpha.extend([42,4])
print(alpha)
(21,32,12,1,2,7,55]
[21,32,12,1,2,7,55,42,4]
(21,32.12.42,1,2,7,55]
None of these
Skype fe
Answers
Answer:
[21,32,12,1,2,7,55,42,4]
Explanation:
.extend(extra) method of a iterable(like list,tuple) adds extra at the end of the iterable
So, each element of [42,4] gets added(appended) at the end of the list
The output for the following còde will be [21, 32, 12, 1, 2, 7, 55, 42, 4]
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 is 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.