How to Add Elements to Lists in Python using Plus Operator and append() Method
Choosing the right way to grow your lists impacts both readability and performance. While the + operator and .append() method both increase collection size, they behave differently in memory and serve distinct purposes.
Using .append(): In-Place Modificationā
The .append() method modifies the original list directly. It's the standard way to build lists dynamically, especially in loops.
tools = ['Git', 'Docker']
# Modifies the original list
tools.append('Kubernetes')
print(tools) # ['Git', 'Docker', 'Kubernetes']
Appending to a list is an O(1) operation (constant time). Regardless of list size, adding one item to the end remains extremely fast.
Using the + Operator: Concatenationā
The + operator joins two sequences to create an entirely new object. It doesn't modify the originals, making it ideal when immutability matters.
list_a = [1, 2]
list_b = [3, 4]
# Creates a brand new list
result = list_a + list_b
print(list_a) # Still [1, 2]
print(result) # [1, 2, 3, 4]
The + operator has O(n + m) complexity. Every use copies all elements into a new list. Avoid list = list + [item] inside loops because performance degrades as the list grows.
Performance Comparisonā
# ā Slow: O(n²) overall
result = []
for i in range(10000):
result = result + [i] # Creates new list each iteration
# ā
Fast: O(n) overall
result = []
for i in range(10000):
result.append(i) # Modifies in place
Key Differencesā
| Feature | .append() | + Operator |
|---|---|---|
| Behavior | In-place modification | Creates new object |
| Return Value | None | The new list |
| Use Case | Building lists in loops | Joining distinct lists |
| Speed | š O(1) constant | š¢ O(n+m) linear |
| Original List | Modified | Unchanged |
The .extend() Alternativeā
Add multiple elements in-place without creating a new list:
tools = ['Git', 'Docker']
# extend: adds each element individually
tools.extend(['Kubernetes', 'Terraform'])
print(tools) # ['Git', 'Docker', 'Kubernetes', 'Terraform']
# append: adds the list as a single nested element
tools.append(['AWS', 'GCP'])
print(tools) # ['Git', 'Docker', 'Kubernetes', 'Terraform', ['AWS', 'GCP']]
Use .extend() to add multiple items in-place. Use .append() for single items. Use + when you need a new list without modifying the originals.
Quick Referenceā
| Goal | Method | Example |
|---|---|---|
| Add one item | .append(x) | lst.append(5) |
| Add multiple items | .extend([...]) | lst.extend([5, 6]) |
| Join two lists (new) | + | new = a + b |
| Join two lists (in-place) | .extend() | a.extend(b) |
Summaryā
Use .append() for building lists dynamically because it's fast and memory-efficient. Use + when you need a new list without modifying the originals. For adding multiple elements in-place, use .extend(). Avoid list = list + [item] in loops as it creates unnecessary copies and degrades performance.