Python Essentials for AI Engineer

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
a = [1, 2]a.append([3, 4])print(a, len(a))        # [1, 2, [3, 4]] 3b = [1, 2]b.extend([3, 4])print(b, len(b))        # [1, 2, 3, 4] 4tags = ["upi"]tags.extend("kyc")      # a string is an iterable of charactersprint(tags)             # ['upi', 'k', 'y', 'c']tags = ["upi"]tags.append("kyc")print(tags)             # ['upi', 'kyc']

extend accepts any iterable — a list, tuple, set, generator, or a file. append accepts any single object.

+, += and extend

  • a + b creates a new list. The original a is unchanged.
  • a += b and a.extend(b) modify a in place.

The difference matters when another name points at the same list:

Python
a = [1, 2]; alias = aa = a + [3]print(alias)            # [1, 2]     -> a now points at a new lista = [1, 2]; alias = aa += [3]print(alias)            # [1, 2, 3]  -> the shared list was changed

Cost

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
def fetch_page(page):    return [{"txn": f"T{page}-{i}"} for i in range(50)]   # stands in for an HTTP callwrong, right = [], []for page in range(20):    rows = fetch_page(page)    wrong.append(rows)        # adds the whole page as ONE item    right.extend(rows)        # adds the 50 recordsprint(len(wrong), len(right)) # 20 1000

With 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 extend different from +?" — extend changes 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], or list(itertools.chain.from_iterable(pages)).