How to Add Element to List in Python: Simple Guide
To add an element to a list in Python, use the
append() method to add it at the end. You can also use insert() to add at a specific position or extend() to add multiple elements.Syntax
Here are the common ways to add elements to a list:
list.append(element): Addselementto the end of the list.list.insert(index, element): Insertselementat the specifiedindex.list.extend(iterable): Adds all elements fromiterable(like another list) to the end.
python
my_list.append(element) my_list.insert(index, element) my_list.extend(iterable)
Example
This example shows how to add elements using append(), insert(), and extend():
python
my_list = [1, 2, 3] my_list.append(4) # Adds 4 at the end my_list.insert(1, 10) # Inserts 10 at index 1 my_list.extend([5, 6]) # Adds 5 and 6 at the end print(my_list)
Output
[1, 10, 2, 3, 4, 5, 6]
Common Pitfalls
Common mistakes include:
- Using
append()with a list adds the whole list as one element, not individual items. - For adding multiple elements, use
extend()instead ofappend(). - Using an invalid index with
insert()can cause unexpected results (it inserts at the start or end).
python
my_list = [1, 2] my_list.append([3, 4]) # Adds the list as one element print(my_list) # Output: [1, 2, [3, 4]] my_list = [1, 2] my_list.extend([3, 4]) # Adds elements individually print(my_list) # Output: [1, 2, 3, 4]
Output
[1, 2, [3, 4]]
[1, 2, 3, 4]
Quick Reference
Summary of methods to add elements to a list:
| Method | Description | Example |
|---|---|---|
| append(element) | Adds one element at the end | my_list.append(5) |
| insert(index, element) | Inserts element at given index | my_list.insert(0, 10) |
| extend(iterable) | Adds multiple elements at the end | my_list.extend([7, 8]) |
Key Takeaways
Use append() to add a single element at the end of a list.
Use insert() to add an element at a specific position.
Use extend() to add multiple elements from another list or iterable.
append() with a list adds it as one element; use extend() to add items individually.
Invalid insert indexes default to start or end without error.