Q4: Explain the differences between the append() and extend() methods for lists in Python, including their use cases.
A4:
The append() and extend() methods in Python are both used to add elements to a list, but they differ in how they handle the addition of elements:
append()Method:append()adds a single element to the end of the list.- It takes one argument, which is the element to be added.
- The element is added as a single item, even if it is a collection (e.g., a list or tuple).
pythonmy_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4]extend()Method:extend()is used to append elements from an iterable (e.g., a list, tuple, or string) to the end of the list.- It takes an iterable as its argument and adds each element of the iterable to the list individually.
pythonmy_list = [1, 2, 3] my_list.extend([4, 5, 6]) print(my_list) # Output: [1, 2, 3, 4, 5, 6]
The choice between append() and extend() depends on the desired outcome. If you want to add a single element, use append(). If you want to add elements from another iterable, use extend(). It's worth noting that using extend() is often more efficient when dealing with large lists because it avoids the need to loop through the elements individually.