append() – Add an Entry to the end of a List

Overview

The append() method in Python is a built-in list method used to add a single item to the end of a list. This method is very useful for dynamically adding elements to a list during runtime, making lists more flexible and capable of handling dynamic data.

Syntax

The syntax for the append() method is straightforward:

list.append(item)
  • list: The name of the list to which you want to add an item.
  • item: The element you want to add to the end of the list.

Basic Usage

The append() method adds the specified item as the last element of the list. Here is an example of how it works:

# Create a list
fruits = ["apple", "banana", "cherry"]

# Append an item to the list
fruits.append("orange")

# Print the list
print(fruits)  # Output: ["apple", "banana", "cherry", "orange"]

Appending Different Data Types

The append() method can add elements of any data type to the list, including integers, strings, floats, lists, and even other objects:

# Create a list with different data types
mixed_list = [1, "hello", 3.14]

# Append an integer
mixed_list.append(10)

# Append a string
mixed_list.append("world")

# Append another list
mixed_list.append([4, 5, 6])

# Print the list
print(mixed_list)  # Output: [1, "hello", 3.14, 10, "world", [4, 5, 6]]

Appending Elements in a Loop

You can use the append() method within a loop to build a list dynamically. This is especially useful when you need to populate a list based on some conditions or inputs over iterations:

# Create an empty list
squares = []

# Append squares of numbers from 0 to 9
for i in range(10):
    squares.append(i**2)

# Print the list
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Performance Considerations

The append() method is efficient for adding elements to the end of a list because it has an average time complexity of O(1). This means that the time it takes to append an element does not significantly increase as the size of the list grows.

Comparison with Other Methods

While append() is used to add a single item to the end of a list, there are other methods to add multiple items or to add items at specific positions:

extend(): Adds multiple items from an iterable (e.g., another list) to the end of the list.

# Create a list
numbers = [1, 2, 3]

# Extend the list with another list
numbers.extend([4, 5, 6])

# Print the list
print(numbers)  # Output: [1, 2, 3, 4, 5, 6]

insert(): Inserts an item at a specified index in the list.

# Create a list
letters = ["a", "b", "d"]

# Insert an item at index 2
letters.insert(2, "c")

# Print the list
print(letters)  # Output: ["a", "b", "c", "d"]

Conclusion

The append() method is a fundamental tool in Python for list manipulation. Its simplicity and efficiency make it ideal for adding elements to a list dynamically.