Question
What is the difference between append() and extend()?
Solution
β Verified
append():
- Adds a single item to the end of the list.
- The item can be of any type (including another list).
- If you append a list, it adds the whole list as one element (nested list).
a = [1, 2, 3] a.append([4, 5]) # Result: [1, 2, 3, [4, 5]]
extend():
- Adds each element from an iterable (like a list, tuple, etc.) to the end of the list.
- It "extends" the list by adding elements one by one.
- If you extend with a list, its items are added individually (not nested).
a = [1, 2, 3] a.extend([4, 5]) # Result: [1, 2, 3, 4, 5]
Click here to download practice questions on
Python Lists