What is the difference between append() and extend() methods in Python?
Rashid D
In Python, theappend() andextend() methods are used to add elements to a list, but they have distinct behaviors. Here's a detailed explanation of the differences between the two methods:
1. append() method: Theappend() method is used to add a single element to the end of a list. It modifies the original list by adding the specified element as a single item.
In the example above, theappend(4) statement adds the element4 to the end of the listmy_list, resulting in[1, 2, 3, 4].
2. extend() method: Theextend() method is used to add multiple elements to the end of a list. It takes an iterable (such as a list, tuple, or string) as an argument and appends each element of the iterable to the original list.
In this example, theextend([4, 5, 6]) statement appends each element[4, 5, 6] individually to the end ofmy_list, resulting in[1, 2, 3, 4, 5, 6].
It's important to note that when usingextend(), the elements of the iterable are added individually to the list, whereasappend() adds the entire iterable as a single element.
As shown in the example,append() adds the entireanother_list as a single element, whereasextend() adds each element ofanother_list individually tomy_list.
In summary,append() adds a single element to the end of a list, whileextend() adds multiple elements from an iterable to the end of a list. Choose the appropriate method based on your specific needs and the desired outcome.