Skip to Content

Python Basics: How Do You Add All Elements from One List to Another in Python?

Which Python Method Combines Two Lists Without Creating a Nested List?

Learn the correct Python method to add all elements from one list to another. Understand the critical difference between .extend() and .append() to avoid common errors like creating nested lists and achieve the desired merged result.

Question

Which method adds all elements of other = [4, 5] to list nums = [1, 2, 3] so that the result is [1, 2, 3, 4, 5]?

A. nums.append(other)
B. nums.insert(other)
C. nums.extend(other)
D. nums.add(other)

Answer

C. nums.extend(other)

Explanation

Extend iterates and appends each element.

The .extend(other) method is used to add all elements from an iterable (like another list) to the end of the current list.

The .extend() method iterates through the provided list (other) and appends each of its items one by one to the end of the original list (nums). This modifies the nums list in-place to produce the desired flat, combined list.

nums = [1, 2, 3]
other = [4, 5]
nums.extend(other)
print(nums) # Output: [1, 2, 3, 4, 5]

The other options are incorrect for the following reasons:

A. nums.append(other) adds the entire other list as a single, nested element to the end of nums. The result would be [1, 2, 3, [4][5]], which is not the goal.

B. nums.insert(other) would raise a TypeError because the .insert() method requires two arguments: an index and the element to insert (insert(index, element)).

D. nums.add(other) would raise an AttributeError. The .add() method is used for adding elements to a set, not a list.

Python Basics: Learn, Apply & Build Programs certification exam assessment practice question and answer (Q&A) dump including multiple choice questions (MCQ) and objective type questions, with detail explanation and reference available free, helpful to pass the Python Basics: Learn, Apply & Build Programs exam and earn Python Basics: Learn, Apply & Build Programs certificate.