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.
What happens if you do
list1 = [1, 2]; list2 = [3, 4]; list1.append(list2)? What does list1 look like? How does it differ fromlist1.extend(list2)?
Answer:
list1.append(list2), the result is: [1, 2, [3, 4]] — the second list was added as a single element (a nested list).list1.extend(list2), the result is: [1, 2, 3, 4] — the elements of the second list are "unpacked" and added as separate elements.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.