Sobes.tech
Junior — Middle

What is the difference between append and extend methods when working with lists in Python?

sobes.tech AI

Answer from AI

The append method adds a single element to the end of the list, making that element the last item.

The extend method takes an iterable object (like a list, tuple) and adds each of its elements to the end of the list separately.

Example:

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

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

Thus, append adds one object as an element, while extend expands the list with elements from the passed iterable object.

What is the difference between append and extend… - sobes.tech