1. Insertion Methods in Lists
Python provides several ways to insert elements into a list. These methods make it easy to add new items at the end, at a specific position, or to combine another list into the current list.
Types of Insertion Methods:
append()— Adds a single element at the end.insert()— Inserts a single element at a specific index.extend()— Adds multiple elements from another list or iterable.
1. append()
The append() method adds a single item to the end of the list.
Syntax:
list_name.append(element)
Example:
fruits = ['apple', 'banana']
fruits.append('mango')
print(fruits)
Output:
['apple', 'banana', 'mango']
Explanation:
append()adds 'mango' at the end.- The original list becomes ['apple', 'banana', 'mango'].
2. insert()
The insert() method inserts an item at a specific position.
Syntax:
list_name.insert(index, element)
Example:
numbers = [10, 20, 30]
numbers.insert(1, 15)
print(numbers)
Output:
[10, 15, 20, 30]
Explanation:
- Original list was
[10, 20, 30]. insert(1, 15)adds 15 at index 1.- So,
20and30shift to the right. - New list becomes [10, 15, 20, 30].
3. extend()
The extend() method adds multiple elements from another list (or any
iterable) to the end.
Syntax:
list_name.extend(iterable)
Example:
list1 = [1, 2, 3]
list2 = [4, 5]
list1.extend(list2)
print(list1)
Output:
[1, 2, 3, 4, 5]
Explanation:
- Original lists were:
list1 = [1, 2, 3]andlist2 = [4, 5]. extend()takes each element from list2 (4and5) and adds them one by one to list1.- So final list becomes [1, 2, 3, 4, 5].
- Note: Unlike
append(), which would add list2 as a single nested list ([1, 2, 3, [4, 5]]),extend()adds each item separately & give result [1, 2, 3, 4, 5].
Summary:
append()➔ Adds one item at the end.insert()➔ Adds one item at a specific position.extend()➔ Adds multiple items from another iterable.