append(), extend(), and insert() methods in Python lists
append(), extend(), and insert() methods in Python lists, along with slicing where applicable.
1. append() Method
Adds a single element to the end of the list.
Examples:
- Adding an integer:pythonnumbers = [1, 2, 3] numbers.append(4) print(numbers) # Output: [1, 2, 3, 4]
- Adding a string:pythonfruits = [“apple”, “banana”] fruits.append(“cherry”) print(fruits) # Output: [“apple”, “banana”, “cherry”]
- Adding a list (as a single element):pythonlist1 = [1, 2] list1.append([3, 4]) print(list1) # Output: [1, 2, [3, 4]]
- Using slicing + append:pythonnums = [10, 20, 30] nums[len(nums):] = [40] # Same as append(40) print(nums) # Output: [10, 20, 30, 40]
2. extend() Method
Adds multiple elements (iterable items) to the end of the list.
Examples:
- Extending with a list:pythonnums = [1, 2] nums.extend([3, 4]) print(nums) # Output: [1, 2, 3, 4]
- Extending with a string (each character is added):pythonletters = [‘a’, ‘b’] letters.extend(“cd”) print(letters) # Output: [‘a’, ‘b’, ‘c’, ‘d’]
- Extending with a tuple:pythonitems = [1, 2] items.extend((3, 4)) print(items) # Output: [1, 2, 3, 4]
- Using slicing + extend:pythonlist1 = [1, 2] list1[len(list1):] = [3, 4] # Same as extend([3, 4]) print(list1) # Output: [1, 2, 3, 4]
3. insert() Method
Inserts an element at a specific position.
Examples:
- Inserting at index 0:pythonnums = [2, 3] nums.insert(0, 1) # Insert 1 at the beginning print(nums) # Output: [1, 2, 3]
- Inserting in the middle:pythonfruits = [“apple”, “cherry”] fruits.insert(1, “banana”) print(fruits) # Output: [“apple”, “banana”, “cherry”]
- Inserting at the end (like
append):pythonnums = [1, 2] nums.insert(2, 3) # Same as append(3) print(nums) # Output: [1, 2, 3] - Using slicing + insert:pythonlist1 = [10, 30] list1[1:1] = [20] # Inserts 20 at index 1 print(list1) # Output: [10, 20, 30]
Key Differences:
| Method | Modifies List? | Adds Single/Multiple Elements? | Position |
|---|---|---|---|
append() | ✅ Yes | Single element (even if it’s a list) | End |
extend() | ✅ Yes | Multiple elements (iterable) | End |
insert() | ✅ Yes | Single element | Specified index |