Open In App

How to add Elements to a List in Python

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Python, adding elements to a list is a common operation that can be done in several ways. One of the simplest methods is using the append() method. In this article we are going to explore different methods to add elements in the list. Below is a simple Python program to add elements to al list using append().

The append() method is the simplest way to add an element to the end of a list. This method can only add one element at a time.

a = [1, 2, 3]

# Add an element 4 at the end of list
a.append(4)
print(a)

Output
[1, 2, 3, 4]

Let’s explore the different methods to add elements to a list.

Using extend() to Add Multiple Elements

If we need to add multiple elements to a list then extend() is a more efficient way than using append() repeatedly.

a = [1, 2, 3]
a.extend([4, 5, 6])

# We can also use list comprehension to first create a list
# of elements then use extend for adding elements
b = [x for x in range(7, 10)]
a.extend(b)

print(a)

Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Using insert() to Add Elements at a Specific Position

If we want to add an element at a specific index in the list then we can use insert() method.

a = [1, 2, 3]

# Here first argument is an index (i.e, 1)
# And second argument is value to be inserted
a.insert(1, 100)
print(a)

Output
[1, 100, 2, 3]

Using List Concatenation to Add Elements

We can also use the + operator to concatenate lists, hence we can use this operator for adding elements into list.

a = [1, 2, 3]
a = a + [4, 5]
print(a)

Output
[1, 2, 3, 4, 5]

Note: This method is less efficient compared to extend(), especially for large lists.

Best Practices for Adding Elements in List

  • Use insert() if we need to place an element at a specific position in the list.
  • Use append() when adding a single item.
  • Use extend() for adding multiple items to avoid the overhead of multiple append() calls.
  • Avoid repeated concatenation, instead of using + to concatenate lists, we can use extend() for better performance.

Read More Operations on List:


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg