How to add a Element in List in Python

Currently i am new to Python and i want to add a Element in List in Python. My goal is to explore various ways to do this such as using append() method, insert() method, and other methods.

1. Add a Element in List in Python using append()

The simplest way to add a element in list in Python is by using the append() method. This method adds an element at the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # Output: [1, 2, 3, 4]

Read also: Best way to Structure Django Templates

2. Using insert() to Add a Element in List in Python

If you need to insert an element at a specific position, insert() is the right tool to add a element in list in Python.

my_list = [1, 2, 3]
my_list.insert(1, 'new')
print(my_list)  # Output: [1, 'new', 2, 3]

3. Add a Element in List in Python with extend()

A extend() method is used to when you want to add a element in list in Python that are iterable, such as another list.

my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list)  # Output: [1, 2, 3, 4, 5]

I hope this article on add a Element in List in Python will help you.

For more information read W3 Schools