Skip to main content

Posts

Differentiate Between append() and extend()

Differentiate Between append() and extend() In Python, both append() and extend() are methods that can be used to add elements to a list. However, there is a key difference between the two methods. The append() method is used to add a single element to the end of the list. The element can be of any data type, including another list. When you call the append() method with an argument, it is added as a single element to the end of the list. For example, consider the following code: In [1]: my_list = [ 1 , 2 , 3 ] my_list . append ( 4 ) print ( my_list ) [1, 2, 3, 4] The output of this code will be [1, 2, 3, 4]. On the other hand, the extend() method is used to add multiple elements to the end of the list. The elements can be provided as a list or any other iterable data type. When you call the extend() method with an argument, it is added as indiv...