When working with Python lists, adding elements is one of the most common operations. Python provides multiple ways to do this, and beginners often get confused between:
Although they look similar, they behave very differently in terms of:
how many elements are added
whether a new list is created
performance and memory usage
In this blog post, we’ll break down these differences with clear examples, diagrams-in-words, and interview tips.
Understanding Python Lists (Quick Recap)
A Python list is:
Ordered
Mutable
Can store mixed data types
my_list = [1, 2, 3]
Let’s see how each method works when we want to add data to a list.
1️⃣ append() – Add ONE element
What it does
append() adds exactly one element to the end of the list.
Modifies the original list
The element can be any object (number, string, list, tuple, etc.)
Syntax
list.append(element)
Example
a = [1, 2, 3]
a.append(4)
print(a)
Output
[1, 2, 3, 4]
Appending a list
a = [1, 2]
a.append([3, 4])
print(a)
Output
[1, 2, [3, 4]]
🔹 The entire list [3, 4] is added as one single element.
2️⃣ extend() – Add MULTIPLE elements
What it does
extend() adds elements from another iterable (list, tuple, string, etc.) one by one.
Modifies the original list
Iterates over the given iterable
Syntax
list.extend(iterable)
Example
a = [1, 2, 3]
a.extend([4, 5])
print(a)
Output
[1, 2, 3, 4, 5]
Extending with a string (important!)
a = []
a.extend("AI")
print(a)
Output
['A', 'I']
🔹 Since strings are iterable, each character is added separately.
3️⃣ + Operator – Create a NEW list
What it does
The + operator concatenates two lists and returns a new list.
Does not modify the original list
Both operands must be lists
Syntax
new_list = list1 + list2
Example
a = [1, 2, 3]
b = a + [4, 5]
print(b)
print(a)
Output
[1, 2, 3, 4, 5]
[1, 2, 3]
🔹 a remains unchanged.
4️⃣ Side-by-Side Comparison
5️⃣ Memory & Performance Considerations ⚡
❌ Inefficient approach
a = []
for i in range(5):
a = a + [i]
🔻 Creates a new list on every iteration
✅ Best practice
a = []
for i in range(5):
a.append(i)
✔ Modifies the same list
✔ Faster and memory-efficient
6️⃣ Interview Trick Question 🚨
a = [1, 2]
b = a
a = a + [3]
print(b)
Output
[1, 2]
Why?
+ creates a new list
b still points to the old list
Now compare with append():
a = [1, 2]
b = a
a.append(3)
print(b)
Output
[1, 2, 3]
Because both a and b reference the same list object.
7️⃣ When to Use What? (Practical Rule)
✅ Use append()
When adding one item
Inside loops
✅ Use extend()
When merging elements from another iterable
When you want to modify the existing list
✅ Use + operator
When you want a new list
When immutability or clarity matters
Final Memory Trick 🧠
append → ONE
extend → MANY
+ → NEW LIST
No comments:
Post a Comment