JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

How to add an element to the front of a list in Python

Author:JIYIK Last Updated:2025/05/05 Views:

This tutorial explains how to insert an element to the front of a list in Python. This tutorial also lists some sample codes to help you understand.


insert()Use the method to insert an element to the front of a list in Python

insert()One of the most commonly used methods is using . It is provided insert()by listthe library. list.insert(pos, element)It takes two parameters, posand elementas parameters. posIt defines the position of the element.

The following is sample code using this method.

lists = ["james", "tim", "jin"]
lists.insert(0, "steve")

print(lists)

Output:

['steve', 'james', 'tim', 'jin']

However, list.insert()the operation consumes a lot of time. To improve the time performance, we can use collections.dequethe method.


deque.appendleft()Use the method to insert an element to the front of a list in Python

Python's collectionsadd_on module provides a variety of functions. In Python 2.4, collectionsadd_on was added deque(), a double-ended queue. It is a list-like container that is efficient in appending and popping. dequeThe add_on function has a single appendleft(element)method. It accepts an element and appends it to the beginning of the list.

The sample code for this method is given below.

import collections

dequeue = collections.deque([5, 2, 6, 8, 1])
print(dequeue)

dequeue.appendleft(10)
print(dequeue)

Output:

deque([5, 2, 6, 8, 1])
deque([10, 5, 2, 6, 8, 1])

Create a new list in Python and append it to the list

A very simple and trivial solution is to create a new list with the desired element x at index 0 of the list. Of course, you don't prepend x to the list, but create a new list with x already at the first position of the list.

The basic code for this approach is given below.

lists = ["james", "tim", "jin"]
new_list = ["x"] + lists
print(new_list)

Output:

['x', 'james', 'tim', 'jin']

Use list slicing in Python to insert elements to the front of a list

List slicing is another way to prepend elements to a list. An element is prepended to the list by assigning the 0th element to it.

The sample code of this method is as follows.

temp_list = [4, 5, 8, 10, 13]

print(temp_list)
temp_list[:0] = [12]

print(temp_list)

Output:

[4, 5, 8, 10, 13]
[12, 4, 5, 8, 10, 13]

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial