What is the difference between Python's list methods append and extend?
Difference Between Python's List Methods append
and extend
In Python, lists have several methods for adding elements. Two commonly used methods are append
and extend
. Although they both add elements to a list, they operate differently. Understanding these differences is crucial for manipulating lists effectively.
append
The append
method adds a single element to the end of the list. This element can be of any data type (another list, a number, a string, etc.).
Syntax:
list.append(element)
Example:
my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] # Appending a list my_list.append([5, 6]) print(my_list) # Output: [1, 2, 3, 4, [5, 6]]
extend
The extend
method adds elements from an iterable (such as another list, a tuple, a set, etc.) to the end of the list. Unlike append
, extend
iterates over its argument and adds each element to the list.
Syntax:
list.extend(iterable)
Example:
my_list = [1, 2, 3] my_list.extend([4, 5, 6]) print(my_list) # Output: [1, 2, 3, 4, 5, 6] # Extending with a string (iterable of characters) my_list.extend('abc') print(my_list) # Output: [1, 2, 3, 4, 5, 6, 'a', 'b', 'c']
Key Differences
-
Functionality:
append
adds its argument as a single element to the end of the list. The length of the list increases by one.extend
iterates over its argument, adding each element to the list. The length of the list increases by however many elements were in the iterable.
-
Type of Argument:
append
can take any type of object as its argument.extend
requires an iterable (list, tuple, string, etc.) as its argument.
-
Resulting Structure:
append
can result in a nested list if a list is appended.extend
always flattens the iterable into the list.
Example Comparison
Let's compare append
and extend
with an example to highlight their differences:
my_list = [1, 2, 3] # Using append my_list.append([4, 5]) print(my_list) # Output: [1, 2, 3, [4, 5]] # Resetting the list my_list = [1, 2, 3] # Using extend my_list.extend([4, 5]) print(my_list) # Output: [1, 2, 3, 4, 5]
Summary
-
append
:- Adds its argument as a single element to the end of the list.
- Increases the list's length by one.
- Argument can be any type of object.
-
extend
:- Iterates over its argument, adding each element to the list.
- Increases the list's length by the number of elements in the iterable.
- Requires an iterable (list, tuple, string, etc.) as its argument.
Understanding these differences helps in choosing the right method for adding elements to a list based on the desired outcome. For more detailed tutorials and practical examples on Python and other programming concepts, consider exploring Grokking the Coding Interview on DesignGurus.io, which provides comprehensive courses on essential coding and interview techniques.
GET YOUR FREE
Coding Questions Catalog