How to use append() in Python

A guide to Python's append() method. Learn different techniques, tips, see real-world applications, and how to debug common errors.

How to use append() in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Tue
Feb 10, 2026
The Replit Team Logo Image
The Replit Team

You will often need to add elements to a list in Python. The built-in append() method offers a simple and efficient way to dynamically grow your data collections.

You'll learn the core technique, discover practical tips, and see real-world applications. You will also get advice to debug common issues and master list manipulation in your projects.

Basic usage of the append() method

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)--OUTPUT--[1, 2, 3, 4]

The append() method modifies the list "in-place," a crucial concept for mutable objects in Python. When you call my_list.append(4), you aren't creating a new list. Instead, you're directly altering the original my_list in memory.

This behavior has a couple of important implications:

  • Efficiency: It's memory-efficient because Python doesn't need to allocate space for a new list.
  • Permanence: The change is permanent. Any other variable that references the same list object will also see the appended element.

Common ways to use append()

The true utility of append() emerges when you combine it with loops and conditional logic, or see how list comprehensions offer a more concise alternative.

Using append() in a loop

numbers = [10, 20]
for i in range(3, 6):
numbers.append(i * 10)
print(numbers)--OUTPUT--[10, 20, 30, 40, 50]

This is a common pattern for building up a list dynamically. The for loop iterates through the numbers generated by range(3, 6)—specifically 3, 4, and 5. In each pass, you calculate a new value and add it to the numbers list.

  • The expression i * 10 is evaluated on each iteration.
  • The append() method then adds this result to the end of the list.

This process repeats until the loop finishes, growing the list from its initial state with the newly calculated values.

Combining append() with conditional statements

fruits = ["apple", "banana"]
new_fruit = "orange"
if len(new_fruit) > 3:
fruits.append(new_fruit)
print(fruits)--OUTPUT--['apple', 'banana', 'orange']

You can control when an element gets added to a list by placing the append() call inside an if statement. This lets you add items only when specific criteria are met. This pattern is incredibly useful for filtering data before it ever enters your list.

  • The condition—in this case, len(new_fruit) > 3—acts as a gatekeeper.
  • The append() method only runs if the condition evaluates to True, giving you precise control over your list's contents.

Using list comprehension with append()

original = [1, 2, 3, 4, 5]
evens = []
[evens.append(num) for num in original if num % 2 == 0]
print(evens)--OUTPUT--[2, 4]

While you can use a list comprehension to call append(), it's an unconventional approach. This syntax combines the loop and conditional logic into a single, dense line to populate the evens list based on the contents of original.

  • The code iterates through original, and the if num % 2 == 0 clause filters for even numbers.
  • For each match, it executes evens.append(num), adding the number to the separate evens list.

The list comprehension itself produces a new list containing None for each appended item, which is then discarded. A more standard approach would build the list directly, like evens = [num for num in original if num % 2 == 0].

Advanced append() techniques

The append() method's utility extends beyond simple lists, proving just as essential when you're managing nested data structures and custom objects.

Appending to nested data structures

user_data = {"Alice": [], "Bob": []}
user_data["Alice"].append("Task 1")
user_data["Bob"].append("Task 2")
print(user_data)--OUTPUT--{'Alice': ['Task 1'], 'Bob': ['Task 2']}

This example shows how append() works on lists nested inside other data structures, like a dictionary. It's a two-step process: you first access the list you want to modify, then call the method directly on it.

  • The expression user_data["Alice"] retrieves the list associated with the key "Alice".
  • Then, .append("Task 1") adds the new task to that specific list, modifying the dictionary in place.

Working with multi-dimensional lists

matrix = [[1, 2], [3, 4]]
matrix.append([5, 6])
matrix[0].append(7)
print(matrix)--OUTPUT--[[1, 2, 7], [3, 4], [5, 6]]

When you're dealing with a list of lists, or a matrix, append() can work at different levels. You can either add a new list to the main container or add an element to one of the nested lists inside it.

  • The call matrix.append([5, 6]) adds the entire list [5, 6] as a new item to the end of the matrix.
  • In contrast, matrix[0].append(7) first selects the inner list at index 0 and then adds the integer 7 to it.

This distinction is key for building and modifying complex, multi-dimensional data structures.

Appending custom objects to lists

class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x},{self.y})"

points = []
points.append(Point(1, 2))
points.append(Point(3, 4))
print(points)--OUTPUT--[Point(1,2), Point(3,4)]

You can append more than just built-in types like numbers and strings to a list. This example shows how to add instances of a custom class, Point, to a list named points. The list becomes a collection of your custom objects.

  • Each time you call points.append(Point(x, y)), you're creating a new Point object and adding it to the end of the list.
  • The custom __repr__ method in the Point class is what gives you the clean, readable output when you print the list.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the list-building techniques using append() we've explored, Replit Agent can turn them into production-ready tools. For example, you could build:

  • A data validation tool that iterates through raw input and appends only clean, formatted entries to a new list.
  • A simple task manager where new to-do items are appended to user-specific lists within a nested dictionary.
  • A simulation that dynamically appends custom objects, like new particles or agents, into the environment during runtime.

Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.

Common errors and challenges

While append() is straightforward, you can run into common issues like TypeError, reference problems, or confusion with the extend() method.

Fixing TypeError when using append() on non-list objects

The append() method belongs exclusively to lists, so trying to use it on another data type like a dictionary will trigger a TypeError. This error simply means the object doesn't support the operation. The code below shows this common mistake.

user_data = {"name": "Alice", "scores": [85, 90]}
user_data.append({"role": "admin"}) # TypeError: 'dict' object has no attribute 'append'

The code tries to call append() on the user_data dictionary directly, but this method only works on lists. To fix this, you must first select the list you intend to modify. The corrected code below shows how.

user_data = {"name": "Alice", "scores": [85, 90]}
user_data["scores"].append(95)
print(user_data) # {'name': 'Alice', 'scores': [85, 90, 95]}

The fix is to target the list inside the dictionary directly. Instead of calling append() on the entire dictionary, you first access the list with user_data["scores"]. Then, you can successfully append the new score. This error often pops up when you're managing complex data structures. It's a good reminder to always make sure you're calling methods on the correct object type—in this case, a list and not a dictionary.

Avoiding reference issues when appending mutable objects

Avoiding reference issues when appending mutable objects

When you append a mutable object like a list multiple times, you're not adding copies. You're adding references to the exact same object. This means a change in one place unexpectedly affects all other references, leading to subtle bugs.

matrix = []
row = [0, 0, 0]
for i in range(3):
matrix.append(row)
matrix[0][0] = 1 # Changes all rows!
print(matrix) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Because the row list is defined outside the loop, you're appending the same reference three times. Any change to one element, like matrix[0][0], affects all of them. See how to fix this below.

matrix = []
for i in range(3):
matrix.append([0, 0, 0]) # Create a new list each time
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

The fix is to create a new list, [0, 0, 0], inside the loop. By doing this, each call to append() adds a unique list object, not just another reference to the same one. Now, changing one inner list won't accidentally alter the others. This is a crucial pattern to remember whenever you're building nested lists or appending any mutable object, like a dictionary, inside a loop.

Understanding when to use append() vs extend()

It's easy to confuse append() with extend() when you want to merge two lists. The append() method adds its argument as a single item, which can create an unwanted nested list. The code below shows what happens when you try this.

numbers = [1, 2, 3]
more_numbers = [4, 5]
numbers.append(more_numbers)
print(numbers) # [1, 2, 3, [4, 5]] - not what was expected!

The append() method treats more_numbers as a single element, creating a nested list instead of merging the items. This is rarely the goal when combining lists. The code below shows the correct way to achieve this.

numbers = [1, 2, 3]
more_numbers = [4, 5]
numbers.extend(more_numbers)
print(numbers) # [1, 2, 3, 4, 5]

The extend() method is the correct tool here. It iterates through the second list and adds each of its elements to the first one, creating a single, merged list. This is different from append(), which adds the entire list as one nested item. You'll want to reach for extend() anytime you need to combine the contents of two lists without creating a nested structure. It keeps your data flat and predictable.

Real-world applications

Now that you've navigated the common errors, you can see how append() is used to build practical, data-driven applications.

Collecting user feedback with append()

You can create interactive scripts that gather data, like customer ratings, by using append() inside a loop to add each new entry to a growing list.

feedback_responses = []

# Collect ratings from users
for i in range(3):
rating = int(input(f"Rate our service (1-5) - User {i+1}: "))
feedback_responses.append(rating)

average_rating = sum(feedback_responses) / len(feedback_responses)
print(f"All ratings: {feedback_responses}")
print(f"Average rating: {average_rating:.1f}/5")

This script demonstrates a common data collection pattern. It initializes an empty list, feedback_responses, to hold user input.

  • A for loop runs three times, each time prompting a user for a numerical rating using the input() function.
  • The append() method then adds each new rating to the list as it's collected.

After the loop concludes, the script calculates the average rating by dividing the list's total from sum() by its item count from len(). Finally, it prints both the complete list of ratings and the formatted average.

Building a stock portfolio tracker with append()

The append() method is also ideal for managing structured data, letting you add dictionaries that represent individual stocks to a growing portfolio list.

# Stock portfolio tracker
portfolio = []

# Add stocks to portfolio
portfolio.append({"symbol": "AAPL", "shares": 10, "price": 150.75})
portfolio.append({"symbol": "GOOG", "shares": 5, "price": 2750.25})
portfolio.append({"symbol": "MSFT", "shares": 15, "price": 305.50})

# Calculate total portfolio value
total_value = 0
for stock in portfolio:
stock_value = stock["shares"] * stock["price"]
total_value += stock_value
print(f"{stock['symbol']}: {stock['shares']} shares at ${stock['price']:.2f} = ${stock_value:.2f}")

print(f"Total portfolio value: ${total_value:.2f}")

This script builds a simple portfolio tracker. It starts by creating an empty list, portfolio, and then populates it by appending three separate dictionaries, each containing details for one stock.

  • A for loop iterates through each dictionary in the portfolio list.
  • Inside the loop, it calculates the value of each holding by multiplying the shares and price.
  • It adds this amount to a running total_value and prints a formatted summary for each stock.

After processing all stocks, the script prints the final combined value of the entire portfolio.

Get started with Replit

Turn your knowledge of append() into a real tool. Describe what you want to build to Replit Agent, like “a simple expense tracker” or “a script that filters and appends valid emails to a new list”.

The agent writes the code, tests for errors, and deploys your application. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.