Python list.append() function


The list.append() method in Python is used to add a single element to the end of a list. It modifies the original list in place and does not return a new list. This method is a convenient way to grow a list dynamically.

Syntax

list.append(element)
  • Parameters:
    • element: The item to be added to the end of the list. This can be any data type, including numbers, strings, lists, or even objects.

Return Value

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

Example Usage

  1. Appending a Single Element:

    my_list = [1, 2, 3] my_list.append(4) # Appending an integer print(my_list) # Output: [1, 2, 3, 4]
  2. Appending Different Data Types:

    my_list = ['apple', 'banana'] my_list.append(3.14) # Appending a float my_list.append(True) # Appending a boolean print(my_list) # Output: ['apple', 'banana', 3.14, True]
  3. Appending a List as a Single Element: When you append a list to another list, the entire list is added as a single element:

    my_list = [1, 2, 3] my_list.append([4, 5]) # Appending a list print(my_list) # Output: [1, 2, 3, [4, 5]]
  4. Using append() in a Loop: You can use append() in a loop to build a list:

    my_list = [] for i in range(5): my_list.append(i) # Appending integers 0 to 4 print(my_list) # Output: [0, 1, 2, 3, 4]
  5. Appending None: You can also append None, which can be useful for initializing or signaling:

    my_list = [1, 2] my_list.append(None) print(my_list) # Output: [1, 2, None]

Summary

  • list.append() is a simple and efficient way to add an element to the end of a list in Python.
  • It can accept various data types, including other lists, allowing for flexible data structures.
  • The method modifies the list in place, making it a common choice for dynamically constructing lists.