What is the difference between `append()` and `extend()`

The `append()` and `extend()` methods are both used to add elements to a list in Python, but they serve different purposes.

  • append(): This method adds a single element to the end of the list. The element can be of any data type, including another list.
  • extend(): This method takes an iterable (like a list, tuple, or set) and adds each of its elements to the list. It effectively extends the list by appending elements from the iterable.

Here is an example demonstrating the difference:

$list = [1, 2, 3]; $list.append(4); // list becomes [1, 2, 3, 4] $list.extend([5, 6]); // list becomes [1, 2, 3, 4, 5, 6]

Python append extend list methods programming