Adding Elements to a List
1. append()
Adds a single element to the end of the list. This is the fastest and most common way to add items.
python tasks = ['Buy groceries', 'Walk dog'] tasks.append('Do laundry') print(tasks) # ['Buy groceries', 'Walk dog', 'Do laundry']
2. insert()
Adds a single element at a specified index. The syntax is list.insert(index, element).
python numbers = [1, 2, 4]
Insert 3 at index 2
numbers.insert(2, 3) print(numbers) # [1, 2, 3, 4]
Insert at the beginning
numbers.insert(0, 0) print(numbers) # [0, 1, 2, 3, 4]
3. List Concatenation (+ Operator)
Creates a new list by joining two existing lists.
python list_a = [10, 20] list_b = [30, 40] list_c = list_a + list_b print(list_c) # [10, 20, 30, 40]
4. Extending a List (.extend())
Adds all elements from another iterable (like another list) to the end of the current list, modifying the original list in place.
python list_a = [1, 2] list_b = [3, 4] list_a.extend(list_b) print(list_a) # [1, 2, 3, 4] print(list_b) # [3, 4] (list_b remains unchanged)