Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is the difference between append() and extend()?
What you need to know
Python
1a = [1, 2]2a.append([3, 4])3print(a, len(a)) # [1, 2, [3, 4]] 345b = [1, 2]6b.extend([3, 4])7print(b, len(b)) # [1, 2, 3, 4] 489tags = ["upi"]10tags.extend("kyc") # a string is an iterable of characters11print(tags) # ['upi', 'k', 'y', 'c']12tags = ["upi"]13tags.append("kyc")14print(tags) # ['upi', 'kyc']extend accepts any iterable — a list, tuple, set, generator, or a file. append accepts any single object.
+, += and extend
a + bcreates a new list. The originalais unchanged.a += banda.extend(b)modifyain place.
The difference matters when another name points at the same list:
Python
1a = [1, 2]; alias = a2a = a + [3]3print(alias) # [1, 2] -> a now points at a new list4a = [1, 2]; alias = a5a += [3]6print(alias) # [1, 2, 3] -> the shared list was changedCost
append is O(1) on average. extend is O(k) for k new items, but it is faster than k separate append calls because the loop runs in C and the list grows its memory once.
A real-life example
You fetch transactions from a paginated payments API: 20 pages of 50 records each.
Python
1def fetch_page(page):2 return [{"txn": f"T{page}-{i}"} for i in range(50)] # stands in for an HTTP call34wrong, right = [], []5for page in range(20):6 rows = fetch_page(page)7 wrong.append(rows) # adds the whole page as ONE item8 right.extend(rows) # adds the 50 records910print(len(wrong), len(right)) # 20 1000With append, len(wrong) reports 20 "transactions", and the next step — for row in wrong: row["txn"] — crashes with TypeError: list indices must be integers or slices, not str, because each "row" is really a page. extend gives the flat list of 1,000 records the rest of the pipeline expects.
Follow-up questions to expect
- "How is
extenddifferent from+?" —extendchanges the list in place;+builds a new list and leaves both inputs unchanged. - "What does
lst.extend("abc")do?" — Adds'a','b'and'c'as three items, because a string is an iterable of characters. - "How do you flatten a list of lists?" —
[x for page in pages for x in page], orlist(itertools.chain.from_iterable(pages)).