JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

How to Replace an Element in a Python List

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

We can replace elements in Python lists in many ways. We can use Python list element indexing, for loops, map functions, and list comprehensions.

This article will discuss the above methods to find and replace elements in Python lists.


Searching and replacing Python list elements using list indexing

Let's take the following list as an example and 0change the element at index from 5 to 20.

my_list = [5, 10, 7, 5, 6, 8, 5, 15]

We will 0change the element at index from 5 to 20.

The sample code is as follows.

my_list = [5, 10, 7, 5, 6, 8, 5, 15]
my_list[0] = 20

print(my_list)

Output:

[20, 10, 7, 5, 6, 8, 5, 15]

forFind and replace elements in a Python list using loop method

We use the function in this method enumerate(). It returns an enumeration object which also contains the counter and the element. When we combine enumerate()the function with the loop, it iterates over the object and gets the index along with the element.forenumerate

The code is

my_list = [5, 10, 7, 5, 6, 8, 5, 15]
for index, value in enumerate(my_list):
    if value == 5:
        my_list[index] = 9

print(my_list)

Output:

[9, 10, 7, 9, 6, 8, 9, 15]

Find and Replace Python List Elements Using List Comprehensions

In this method, we can generate a new list by applying pre-defined conditions on the old list.

The syntax is:

my_list = [5, 10, 7, 5, 6, 8, 5, 15]

[9 if value == 5 else value for value in my_list]

print(my_list)

Output:

[9, 10, 7, 9, 6, 8, 9, 15]

mapFind and replace elements in a Python list using the

This method changes the element of the second list item by the index of the first list item.

The code is:

list_1 = [5, 10, 7]
list_2 = [7, 10, 7, 5, 7, 5, 10]

ent = {k: i for i, k in enumerate(list_1)}
result = list(map(ent.get, list_2))

print("list2 after replacement is:", result)

Output:

list2 after replacement is: [2, 1, 2, 0, 2, 0, 1]

in conclusion

  1. List indexing is good when we want to replace an element in a list.
  2. When we want to replace multiple elements in a list based on a selectivity criterion, list comprehensions are the right choice.
  3. The use of round-robin is discouraged as it requires more execution time and memory.

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

Read the first line of a file in Python

Publish Date:2025/05/05 Views:192 Category:Python

In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t

Convert Tensor to NumPy array in Python

Publish Date:2025/05/03 Views:86 Category:Python

This tutorial will show you how to convert a Tensor to a NumPy array in Python. Use the function in Python Tensor.numpy() to convert a tensor to a NumPy array Eager Execution of TensorFlow library can be used to convert tensor to NumPy arra

Saving NumPy arrays as images in Python

Publish Date:2025/05/03 Views:194 Category:Python

In Python, numpy module is used to manipulate arrays. There are many modules available in Python that allow us to read and store images. An image can be thought of as an array of different pixels stored at specific locations with correspond

Transposing a 1D array in NumPy

Publish Date:2025/05/03 Views:98 Category:Python

Arrays and matrices form the core of this Python library. The transpose of these arrays and matrices plays a vital role in certain topics such as machine learning. In NumPy, it is easy to calculate the transpose of an array or a matrix. Tra

Find the first index of an element in a NumPy array

Publish Date:2025/05/03 Views:59 Category:Python

In this tutorial, we will discuss how to find the first index of an element in a numpy array. Use where() the function to find the first index of an element in a NumPy array The function in the numpy module where() is used to return an arra

Remove Nan values from NumPy array

Publish Date:2025/05/03 Views:119 Category:Python

This article discusses some built-in NumPy functions that you can use to remove nan values. Remove Nan values ​​using logical_not() and methods in NumPy isnan() logical_not() is used to apply logical NOT to the elements of an array. isn

Normalizing a vector in Python

Publish Date:2025/05/03 Views:51 Category:Python

A common concept in the field of machine learning is to normalize a vector or dataset before passing it to the algorithm. When we talk about normalizing a vector, we say that its vector magnitude is 1, being a unit vector. In this tutorial,

Calculating Euclidean distance in Python

Publish Date:2025/05/03 Views:128 Category:Python

In the world of mathematics, the shortest distance between two points in any dimension is called the Euclidean distance. It is the square root of the sum of the squares of the differences between the two points. In Python, the numpy, scipy

Element-wise division in Python NumPy

Publish Date:2025/05/03 Views:200 Category:Python

This tutorial shows you how to perform element-wise division on NumPy arrays in Python. NumPy Element-Wise Division using numpy.divide() the function If we have two arrays and want to divide each element of the first array with each element

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial