PYTHON

The Python List append() Method: Syntax, Usage, and Examples

In Python, append() is a list method that adds a single element to the end of a list.

How to Use append() in Python Lists

The syntax of using the append() method in the Python programming language is simple and straightforward. Here’s a basic example:

# Creating a list of strings and appending an item
fruits = ['apple', 'banana']
fruits.append('cherry')  # Adds 'cherry' to the end of the list
print(fruits)  # Outputs: ['apple', 'banana', 'cherry']

When to Use append() in Python Lists

Building Lists

When collecting or generating data in a loop, append() can add an element at a time to a list. Once you’ve created a list using square brackets ([]), you can use the append() method on it.

squares = []
for i in range(5):
    squares.append(i**2)  # Appends the square of i

Aggregating Results

In data processing and handling, append() is useful for aggregating results into a single list.

results = []
for experiment in experiments:
    result = run_experiment(experiment)
    results.append(result)  # Collects each experiment's result

User Input Collection

append() is ideal for scenarios requiring the collection of user inputs. As an example, consider responses to survey questions or user preferences.

responses = []
while True:
    response = input("Enter your response (or 'done' to finish): ")
    if response == 'done':
        break
    responses.append(response)

Examples of Using append() in Python Lists

E-commerce Shopping Cart

In e-commerce platforms, append() can manage shopping cart functionality, allowing users to add items as they browse.

shopping_cart = []
shopping_cart.append('T-shirt')  # User adds a T-shirt to the cart
shopping_cart.append('Jeans')  # User adds Jeans to the cart

Data Collection in Scientific Research

In scientific research, data points accumulate over time. In such cases, append() can add the data points in an ordered list at the time of measurement.

measurements = []
for _ in range(10):
    measurement = collect_measurement()
    measurements.append(measurement)  # Stores each new measurement

Social Media Applications

In social media applications, append() can add new posts or comments to a user's feed or comment section.

comments = []
comments.append("Great photo!")  # A user adds a new comment
comments.append("Love this!")  # Another user adds a comment

Learn More About the Python List append() Method

Appending Various Data Types

The append() method allows you to add items of any data type. This includes numbers, strings, and even other lists or complex objects.

# Appending different data types
numbers = [1, 2, 3]
numbers.append(4)  # Appends an integer

strings = ['hello']
strings.append('world')  # Appends a string

# Appending a list
lists = [[1, 2], [3, 4]]
lists.append([5, 6])  # Appends a list

Appending vs. Extending Lists

The append() method adds its argument as a single item to the end of a list. By contrast, the list extend() method unpacks the argument and adds each element to the list. This is useful when you need to combine two lists or add multiple elements to an existing list at once.

# Using append()
list1 = ['a', 'b', 'c']
list1.append(['d', 'e'])
print(list1)  # Outputs: ['a', 'b', 'c', ['d', 'e']]

# Using extend()
list2 = ['a', 'b', 'c']
list2.extend(['d', 'e'])
print(list2)  # Outputs: ['a', 'b', 'c', 'd', 'e']

Caveats of Using append()

Appending Strings in Python

The append() method is only available to lists. Python strings are immutable and have no append() function. To modify or concatenate strings, you need to use string concatenation or formatting methods.

# Concatenating strings with '+'
base_url1 = "http://example.com"
endpoint1 = "/api/data"
full_url1 = base_url1 + endpoint1
print(full_url1)  # Outputs: "http://example.com/api/data"

# Using format strings for concatenation
base_url2 = "http://example.com"
endpoint2 = "/api/data"
full_url2 = f"{base_url2}{endpoint2}"
print(full_url2)  # Outputs: "http://example.com/api/data"
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH