ProgrammingPython Developer

What is the difference between the append() and extend() methods for lists in Python? Provide examples where misunderstanding leads to logical errors.

Pass interviews with Hintsage AI assistant

Answer.

The append() and extend() methods for lists in Python are used to add elements, but they do so in fundamentally different ways:

  • append(obj) adds a single element (any object — including a list) to the end of the original list.
  • extend(iterable) adds all elements of the iterable object one by one (it "unpacks" it when adding).

Example:

lst = [1, 2, 3] lst.append([4, 5]) # Result: [1, 2, 3, [4, 5]] lst = [1, 2, 3] lst.extend([4, 5]) # Result: [1, 2, 3, 4, 5]

This difference often leads to logical errors when expecting a "flat" list, but getting nested instead.

Trick question.

What happens if you do list1 = [1, 2]; list2 = [3, 4]; list1.append(list2)? What does list1 look like? How does it differ from list1.extend(list2)?

Answer:

  • After list1.append(list2), the result is: [1, 2, [3, 4]] — the second list was added as a single element (a nested list).
  • After list1.extend(list2), the result is: [1, 2, 3, 4] — the elements of the second list are "unpacked" and added as separate elements.

Examples of real errors due to unfamiliarity with the nuances of the topic.


Story

A developer, when combining parsing results from several files, did output.append(parsed_lines). As a result, instead of a long flat list, they received a list of lists (one element for each file), which broke all further processing — in particular, functions expecting a sequence of strings started throwing errors on the input data.


Story

In the project, extend was used to add a string like "foo" (the string was treated as iterable). This led to the characters of the string becoming separate elements of the list: ['f', 'o', 'o'] instead of the desired "foo".


Story

When serializing data for transmission in JSON, append/extend were used in a loop without understanding the difference. As a result, structures were created that violated the schema, causing some microservices to crash during validation or work incorrectly.