The list techniques append and extend behave differently. Here is a detailed comparison append Vs. extend in Python. The append method adds a single element to the end of the list. The extend method adds multiple elements by appending iterable(each item). Both techniques serve to change lists in Python.

Python Lists: append Vs extend

extend vs append python

1. append()

  • Purpose: Adds a single element (object) to the end of the list.
  • Behavior: Treats the argument as a single entity and adds it to the list as-is.
  • Syntax: list.append(element)

Example:

my_list = [1, 2, 3]
my_list.append([4, 5]) # Adds the entire list [4, 5] as a single element
print(my_list) # Output: [1, 2, 3, [4, 5]]

2. extend()

  • Purpose: Adds all elements of an iterable (e.g., list, tuple, string) to the end of the list.
  • Behavior: Iterates the argument and adds each element individually.
  • Syntax: list.extend(iterable)

Example:

my_list = [1, 2, 3]
my_list.extend([4, 5]) # Adds each element of the list [4, 5] individually
print(my_list) # Output: [1, 2, 3, 4, 5]

Key Differences

Featureappend()extend()
AddsA single element to the end of the listEach element of an iterable to the end of the list
ArgumentAn object (could be of any type)An iterable (like a list, tuple, string, etc.)
Resulting ListOriginal list with the added element as-isOriginal list with elements added individually

Extra Examples

Appending a string:

my_list = [1, 2, 3] 
my_list.append("hello")
print(my_list)
# Output: [1, 2, 3, 'hello']

Here, the entire string "hello" is added as a single element.

Extending with a string:

my_list = [1, 2, 3] 
my_list.extend("hello")
print(my_list)

# Output: [1, 2, 3, 'h', 'e', 'l', 'l', 'o'].
Each character of the string "hello" is added separately. Each character becomes a separate element.

When to Use append vs. extend

  • Use the append to add a single item. You can add an entire object, like another list, as a single element.
  • Use the extend to concatenate of another iterable. It could be a list, tuple, or string. You add it to the end of your list.