Lists are mutable, meaning you can change their contents after creation.
1. Add Items with append()
The append() method adds a single item to the end of the list.
numbers = [1, 2, 3] numbers.append(4) print(numbers) # Output: # [1, 2, 3, 4]Use append() when you want to add only one new element.
2. Add Items at a Specific Position with insert()
The insert() method adds an item at a specific index
names = ["Alice", "Bob", "Charlie"] names.insert(1, "David") print(names) # Output: # ['Alice', 'David', 'Bob', 'Charlie']This inserts "David" at index 1 and shifts later items to the right.
3. Add Multiple Items with extend()
The extend() method adds multiple items (from another list or iterable) to the end
a = [1, 2, 3] b = [4, 5, 6] a.extend(b) print(a) # Output: # [1, 2, 3, 4, 5, 6]Use extend() to add all elements from one list to another.
4. Add Items Using List Concatenation
You can join two lists using the + operator
x = ["a", "b"] y = ["c", "d"] z = x + y print(z) # Output: # ['a', 'b', 'c', 'd']This creates a new list without modifying the originals.
5. Add Items in a Loop
You can add items one by one using a loop
nums = [1, 2, 3] for i in range(4, 7): nums.append(i) print(nums) # Output: # [1, 2, 3, 4, 5, 6]This adds numbers 4, 5, and 6 to the list.
6. Add Nested Lists
When you append() a list, it adds the list as a single nested item
lst = [1, 2] lst.append([3, 4]) print(lst) # Output: # [1, 2, [3, 4]]Important Notes
-
append()adds one item at the end. -
insert()adds at a specific position. -
extend()adds multiple items from another iterable. -
List concatenation with
+returns a new list. -
Using a loop gives dynamic insertion based on logic.