Difference between Append, Extend and Insert in PythonList: are like an array of dynamic size, declared in another programming language such as vector in C++ or Arraylist in Java. It is not necessary for a list to be homogeneous, and this is the main reason that makes it the most powerful tool in Python. A single list can contain different data types such as strings, integers, and objects. As we know, lists are mutable, so they can be altered even after creating them. Lists has several methods, among which append(), insert(), extend() are most common ones. In this tutorial, we will learn how append(), expend(), and insert() functions are different from each other in Python's lists. Append() FunctionThe append() function is used for adding an element at the end of the list. The argument we pass in the append() function is added as a single element at the end of the list, and the length of the list will increase by 1. Syntax The "element_1" can be an integer, tuple, string or another list. Example: Output: The added elements in the given list are: ['The', 'list_1', 'is', 'an', 'example'] Insert() FunctionThe insert() function is used for inserting the value at any desired position in the list. We have to pass two arguments in it; the first is for index where we want to inter the element, and the second is for element to be inserted. Syntax The "element_1" can be an integer, tuple, string, or object. Example: Output: The inserted elements in the given list are: ['The', 'list_1', 'is', 'an', 'example'] Extend() FunctionThe extend() function is used for appending each element of the iterable (list, string, or tuple) to the end of the list. This will increase the length of the list by the number of elements of the iterable are passed as an argument. Syntax Example: Output: The extended elements in the given list are: ['The', 'list_1', 'is', 'an', 'example', 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't'] Difference Between Append(), Insert() and Extend()
Let's compare all the three methods in a single program: Output: The appended elements in the given list are: ['this', 'is', 'LIST_1', ['Example_1', 'Example_2']] The inserted elements in the given list are: ['this', 'is', ['Example_1', 'Example_2'], 'of', 'LIST_2'] The extended elements in the given list are: ['this', 'is', 'LIST_3', 'Example_1', 'Example_2'] ConclusionIn this tutorial, we discussed different methods that can be used for modifying lists in Python. We have also explained the difference between append(), insert(), and extend() functions in the list of Python. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India