Which method is used to add the element at specified location in the list in Python?

Inserting an element in list at specific index using list.insert()

In python list provides a member function insert() i.e.

list.insert(position, element)
It accepts a position and an element and inserts the element at given position in the list.

Let’s see an example,

Suppose we have a list of strings i.e.

# List of string list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from']
Now let insert ‘why’ at 3rd position in the list i.e.
# Add an element at 3rd position in the list list1.insert(3, 'why')
Index will start from 0 in list. So, element will be inserted at 3rd position i.e. after 0,1 & 2.
Advertisements

So, list contents will be now,

['Hi', 'hello', 'at', 'why', 'this', 'there', 'from']

Python List insert()

In this tutorial, we will learn about the Python List insert() method with the help of examples.

The insert() method inserts an element to the list at the specified index.

Example

# create a list of vowels vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 (4th position) vowel.insert(3, 'o')
print('List:', vowel) # Output: List: ['a', 'e', 'i', 'o', 'u']

Python Append() to Add Element to the End of List

You can add an element to the last location of the list using the Python append(). The function requires a single argument as the element of the list to insert.

After you execute the code in Python, the element gets added to the end of the list.

1
2
3
myList = [5, "Six", 7, "Eight", 9, "Ten"];
myList.append("Three");
print(myList);

Output

[5, ‘Six’, 7, ‘Eight’, 9, ‘Ten’, ‘Three’]

The above example showing the element added to the end of the list. However, you can add an element to the desired location of the list. To learn how to add an element to the desired location, read further.

Python - Add List Items

❮ Previous Next ❯

Append Items

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Try it Yourself »

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4] >>> insert_at = 2 # Index at which you want to insert item >>> b = a[:] # Created copy of list "a" as "b". # Skip this step if you are ok with modifying the original list >>> b[insert_at:insert_at] = [3] # Insert "3" within "b" >>> b [1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4] >>> insert_at = 2 # Index starting from which multiple elements will be inserted # List of elements that you want to insert together at "index_at" (above) position >>> insert_elements = [3, 5, 6] >>> a[insert_at:insert_at] = insert_elements >>> a # [3, 5, 6] are inserted together in `a` starting at index "2" [1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index(...) is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don't do it this way. It is just for illustration):

>>> a = [1, 2, 4] >>> insert_at = 2 >>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))] >>> b [1, 2, 3, 4]

Python's .append(): Add Items to Your Lists in Place

by Leodanis Pozo Ramos basics python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Building Lists With Python's .append()

Adding items to a list is a fairly common task in Python, so the language provides a bunch of methods and operators that can help you out with this operation. One of those methods is .append(). With .append(), you can add items to the end of an existing list object. You can also use .append() in a for loop to populate lists programmatically.

In this tutorial, you’ll learn how to:

  • Work with .append()
  • Populate lists using .append() and a for loop
  • Replace .append() with list comprehensions
  • Work with .append() in array.array() and collections.deque()

You’ll also code some examples of how to use .append() in practice. With this knowledge, you’ll be able to effectively use .append() in your programs.

Free Download: Get a sample chapter from Python Basics: A Practical Introduction to Python 3 to see how you can go from beginner to intermediate in Python with a complete curriculum, up-to-date for Python 3.8.

Python List insert() - Insert Element At Specified Position

Insert an item at a given position.

The list.insert() method is used to insert a value at a given position in the list.

Syntax:

list.insert(index, value)

Parameters:

  1. index: (Required) The index position where the element has to be inserted.
  2. value: (Required) The value that has to be added. It can be of any type (string, integer, list, tuple, etc.).

Return type:

No return value.

The following example demonstrates the insert() method.

Example:
Copy
cities = ['Mumbai', 'London', 'Paris', 'New York'] cities.insert(0, 'New Delhi') # inserts at 0 index (first element) print(cities) cities.insert(2, 'Chicago') # inserts at 2nd index print(cities)
Output
['New Delhi', 'Mumbai', 'London', 'Paris', 'New York'] ['New Delhi', 'Mumbai', 'Chicago', 'London', 'Paris', 'New York']

The insert method can also insert set and tuples into a list. You can also add dictionaries to a list also.

Example: Insert Tuple and List
Copy
mycities = {'Delhi','Chennai'} favcities = ('Hyderabad','Bangalore') worldcities = ['Mumbai', 'London', 'New York'] worldcities.insert(1, mycities) worldcities.insert(3, favcities) print("Cities: ", cities)
Output
Cities: ['Mumbai', {'Delhi', 'Chennai'}, 'London', ('Hyderabad', 'Bangalore'), 'New York']

When an index is passed that is greater than the length of the list, the insert() method inserts the element at the end of the list.

Example: insert()
Copy
cities = ['Mumbai', 'London', 'Paris', 'New York'] cities.insert(10, 'Delhi') print(cities)
Output
['Mumbai', 'London', 'Paris', 'New York', 'Delhi']