Python list.extend() function


The list.extend() method in Python is used to add multiple elements to the end of a list. Unlike list.append(), which adds a single element, extend() takes an iterable (such as a list, tuple, or string) and appends each of its elements to the original list. This method modifies the original list in place and does not return a new list.

Syntax

list.extend(iterable)
  • Parameters:
    • iterable: An iterable (like a list, tuple, set, or string) whose elements will be added to the list.

Return Value

  • The method does not return a value (None is returned implicitly).

Example Usage

  1. Extending a List with Another List:

    my_list = [1, 2, 3] my_list.extend([4, 5, 6]) # Extending with another list print(my_list) # Output: [1, 2, 3, 4, 5, 6]
  2. Extending with a Tuple:

    my_list = ['a', 'b'] my_list.extend(('c', 'd', 'e')) # Extending with a tuple print(my_list) # Output: ['a', 'b', 'c', 'd', 'e']
  3. Extending with a String: When extending with a string, each character of the string is added as a separate element:

    my_list = ['x', 'y'] my_list.extend('z') # Extending with a string print(my_list) # Output: ['x', 'y', 'z']
  4. Using extend() in a Loop: You can also use extend() to add elements from an iterable dynamically:

    my_list = [] for i in range(5): my_list.extend([i]) # Extending with a list containing the current integer print(my_list) # Output: [0, 1, 2, 3, 4]
  5. Combining Lists: You can use extend() to combine two lists:

    list1 = [1, 2] list2 = [3, 4] list1.extend(list2) # Extending list1 with list2 print(list1) # Output: [1, 2, 3, 4]

Summary

  • list.extend() is a powerful method for adding multiple elements to a list from any iterable.
  • It modifies the original list in place and allows for the combination of various data types.
  • This method is particularly useful when you want to merge lists or append multiple elements at once without nesting them in a new list.