![]() |
VOOZH | about |
Python lists are dynamic, which means we can add items to them anytime. In this guide, we'll look at some common ways to add single or multiple items to a list using built-in methods and operators with simple examples:
append() method adds one item to the end of the list. It modifies the original list in-place.
[1, 2, 3, 4]
Explanation:append() method is used to add the number 4 to the list li. After running the code, the list becomes [1, 2, 3, 4].
extend() method adds each element from an iterable (like a list or tuple) to the end of the existing list.
[1, 2, 3, 4, 5, 6]
Explanation:extend() method adds all items from the iterable (like a list) to the end of the original list. The result will be [1, 2, 3, 4, 5, 6].
insert(index, item) method places the item at the specified position. Existing elements are shifted to the right. We can also use insert() to add multiple items at once.
[1, 10, 2, 3] [1, 6, 5, 4, 2, 3]
Explanation:
The +operator joins two or more lists and returns a new list without modifying the original ones.
[1, 2, 3, 4, 5, 6]
Explanation: The + operator combines the two lists a and b into a new list c. The result is [1, 2, 3, 4, 5, 6] and the original lists remain unchanged.
We can use a loop (like for) to add items conditionally or repeatedly using append().