Difference between append, extend and insert in Python

In Python, a list provides the append(), insert(), and extend() functions. Let's look at the differences between these functions.

1. list.append()

append() adds the item passed as an argument to the end of the list.

In this example, a is added to the end of the list and [1, 2, 3] list is added.

list = [2, 9, 3]

list.append('a')
print(list)

list.append([1, 2, 3])
print(list)

Output:

[2, 9, 3, 'a']
[2, 9, 3, 'a', [1, 2, 3]]

2. list.extend()

extend() adds all the items of an iterable passed as an argument to the list.

In this example, items from list2 and tuple are added to the list.

list = [2, 9, 3]
list2 = [1, 2, 3]
list.extend(list2)
print(list)

tuple = (4, 5, 6)
list.extend(tuple)
print(list)

Output:

[2, 9, 3, 1, 2, 3]
[2, 9, 3, 1, 2, 3, 4, 5, 6]

3. list.insert()

insert(index, item) adds the item to the position of the argument index.

In this example, 'a' is added to index 0 and 'b' is added to index 2.

list = [2, 9, 3]

list.insert(0, 'a')
print(list)

list.insert(2, 'b')
print(list)

Output:

['a', 2, 9, 3]
['a', 2, 'a', 9, 3]
codechachaCopyright ©2019 codechacha