Sobes.tech
Junior — Middle

How do the Append and Extend methods for lists in Python differ in their purpose and behavior?

sobes.tech AI

Answer from AI

The append and extend methods in Python lists are used to add elements, but they work differently:

  • append(obj) adds one object to the end of the list as a single element.

  • extend(iterable) extends the list by adding each element from the passed iterable object separately.

Example:

lst = [1, 2, 3]
lst.append([4, 5])  # lst becomes [1, 2, 3, [4, 5]]
lst.extend([6, 7])   # lst becomes [1, 2, 3, [4, 5], 6, 7]

Thus, append adds the element as a whole, while extend unpacks the iterable object and adds its elements separately.