Как заменить значения в списке в Python
Часто вас может заинтересовать замена одного или нескольких значений в списке в Python.
К счастью, это легко сделать в Python, и в этом руководстве дается несколько различных примеров того, как это сделать.
Пример 1. Замена одного значения в списке
Следующий синтаксис показывает, как заменить одно значение в списке в Python:
Пример 2. Замена нескольких значений в списке
Следующий синтаксис показывает, как заменить несколько значений в списке в Python:
Пример 3. Замена определенных значений в списке
Следующий синтаксис показывает, как заменить определенные значения в списке в Python:
Вы также можете использовать следующий синтаксис для замены значений, превышающих определенный порог:
Точно так же вы можете заменить значения, которые меньше или равны некоторому порогу:
7 Efficient Ways to Replace Item in List in Python
Lists in python are data structures used to store items of multiple types together under the same list. Using a list, we can store several data types such as string values, integer, float, sets, nested lists, etc. The items are stored inside square brackets ‘[ ]’. They are mutable data types, i.e., they can be changed even after they have been created. We can access list elements using indexing. In this article, we shall look into 7 efficient ways to replace items in a python list.
How to replace item in list python
Lists are compelling and versatile data structures. As mentioned above, lists are mutable data types. Even after a list has been created, we can make changes in the list items. This property of lists makes them very easy to work with. Here, we shall be looking into 7 different ways in order to replace item in a list in python.
- Using list indexing
- Looping using for loop
- Using list comprehension
- With map and lambda function
- Executing a while loop
- Using list slicing
- Replacing list item using numpy
1. Using list indexing
The list elements can be easily accessed with the help of indexing. This is the most basic and the easiest method of accessing list elements. Since all the elements inside a list are stored in an ordered fashion, we can sequentially retrieve its elements. The first element is stored at index 0, and the last element is stored at index ‘len(list)-1’.
Let us take a list named ‘my_list’, which stores names of colors. Now, if we want to replace the first item inside the list from ‘Red’ to ‘Black’, we can do that using indexing. We assign the element stored at the 0th index to a new value. Then the list printed would contain the replaced item.
2. Looping using for loop
We can also execute a for loop to iterate over the list items. When a certain condition is fulfilled inside the for loop, we will then replace that list item using indexing.
We shall take the same ‘my_list’ as in the above example. Then, we shall run the for loop for the length of the list ‘my_list’. Inside the loop, we have placed the condition that when the list element equals ‘Orange’, we will replace the item at that index with ‘Black’. Then after the for loop ends, we shall print that list.
The output prints the list with the replaced value.
3. Using list comprehension
List Comprehension in python is a compact piece of code. Using list comprehension, we can generate new sequences from already existing sequences. Instead of writing an entire block of code for executing a for loop or an if-else loop, we can write a single line code for the same.
The syntax for list comprehension is:
It consists of the expression which has to be printed into the new list, the loop statement, and the original list from which the new values will be obtained.
We shall use list comprehension to append the string ‘ color’ to all the list elements of my_list. We shall replace the old values with the updated values.
The list with replaced values is:
4. With map and lambda function
Map() is a built-in function in python using which we can iterate over an iterable sequence without having to write a loop statement.
The syntax of the map is:
Here, every value inside the iterable will be passed into a function, and the map() function will output the inside function’s return value. Inside the map() function, we have taken a lambda function as the first argument.
A lambda function is an anonymous function containing a single line expression. It can have any number of arguments, but only one expression can be evaluated. Here, the lambda function will append the string ‘ color’ for all the items present in the list and return the new value. Then using the list() function, we shall convert the map object returned by the map() function into a list.
The output is:
If we want to replace a particular item in the list, then the code for that will be:
We have used the replace() method to replace the value ‘Orange’ from my_list to ‘Black.’ The output is:
5. Executing a while loop
We can also have a while loop in order to replace item in a list in python. We shall take a variable ‘i’ which will be initially set to zero. The while loop shall execute while the value of ‘i’ is less than the length of the list my_list. We shall use the replace() method to replace the list item ‘Gray’ with ‘Green.’ The variable ‘i’ shall be incremented at the end of the loop.
The updated list is:
6. Using list slicing
We can also perform slicing inside a list. Using slicing enables us to access only a certain part of a list.
The syntax of the list is:
Using list slicing, we can replace a given item inside a list. First, we shall store the index of the item to be replaced into a variable named ‘index.’ Then, using list slicing, we will replace that item with a new value, ‘Green.’
The output is:
7. Replacing list item using numpy
We can also replace a list item using python’s numpy library. First, we will convert the list into a numpy array. Then using numpy’s where() function, we specify a condition according to which we will replace the value. We shall replace the value ‘Gray’ with ‘Green.’ Else, the value will be the same.
The output is:
FAQ’s Related to Replace item in list in Python
Using list comprehension, map-lambda function, replace function, etc., we can perform in-place replacement of list items.
This sums up five different ways of replacing an item in a list. If you have any questions in your mind, then let us know in the comments below.
Python: Replace Item in List (6 Different Ways)
In this tutorial, you’ll learn how to use Python to replace an item or items in a list. You’l learn how to replace an item at a particular index, how to replace a particular value, how to replace multiple values, and how to replace multiple values with multiple values.
Being able to work with lists is an important skill for any Python developer, given how prevalent and understandable these Python data structures are.
By the end of this tutorial, you’ll have learned:
- How to use list assignment to replace an item in a Python list
- How to use for loops and while loops to replace an item in a Python list
- How to replace multiple items in a list
Table of Contents
Replace an Item in a Python List at a Particular Index
Python lists are ordered, meaning that we can access (and modify) items when we know their index position. Python list indices start at 0 and go all the way to the length of the list minus 1.
You can also access items from their negative index. The negative index begins at -1 for the last item and goes from there. To learn more about Python list indexing, check out my in-depth overview here.
If we want to replace a list item at a particular index, we can simply directly assign new values to those indices.
Let’s take a look at what that looks like:
In the next section, you’ll learn how to replace a particular value in a Python list using a for loop.
Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.
Replace a Particular Value in a List in Python Using a For Loop
Python lists allow us to easily also modify particular values. One way that we can do this is by using a for loop.
One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.
Let’s see what this looks like. In our list, the word apple is misspelled. We want to replace the misspelled version with the corrected version.
Let’s take a look at what we’ve done here:
- We loop over each index in the list
- If the index position of the list is equal to the item we want to replace, we re-assign its value
In the next section, you’ll learn how to turn this for loop into a Python list comprehension.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Replace a Particular Value in a List in Python Using a List Comprehension
One of the key attributes of Python list comprehensions is that we can often turn for loops into much shorter comprehensions. Let’s see how we can use a list comprehension in Python to replace an item in a list.
We’ll use the same example we used in the for loop, to help demonstrate how elegant a Python list comprehension can be:
We can see here that there are two main benefits of list comprehensions compared to for loops:
- We don’t need to initialize an empty list
- The comprehension reads in a relatively plain English
In the next section, you’ll learn how to change all values in a list using a formula.
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Change All Values in a List in Python Using a Function
Neither of the approaches above are immediately clear as to what they are doing. Because of this, developing a formula to do this is a helpful approach to help readers of your code understand what it is you’re doing.
Let’s take a look at how we can use the list comprehension approach and turn it into a formula:
Here, we simply need to pass in the list, the item we want to replace, and the item we want to replace it with. The function name makes it easy to understand what we’re doing, guiding our readers to better understand our actions.
In the next section, you’ll learn how to replace multiple values in a Python list.
Replace Multiple Values in a Python List
There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
Let’s take a look at an example where we want to replace all known typos in a list with the word typo .
Similar to the for loop method shown earlier, we check whether or not an item is a typo or not and replace its value.
In the next section, you’ll learn how to replace multiple values in a Python list with different values.
Replace Multiple Values with Multiple Values in a Python List
The approach above is helpful if we want to replace multiple values with the same value. There may be times where you want to replace multiple values with different values.
Looking again at our example, we may want to replace all instances of our typos with their corrected spelling. We can again use a for loop to illustrate how to do this.
Instead of using a single if statement, we’ll nest in some elif statements that check for a value’s value before replacing.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
In this tutorial, you learned how to use Python to replace items in a list. You learned how to use Python to replace an item at a particular index, how to replace a particular value, how to modify all values in a list, and how to replace multiple values in a list.
To learn more about Python list indexing, check out the official documentation here.
Replace Item in List in Python: A Complete Guide
There are three ways to replace an item in a Python list. You can use list indexing or a for loop to replace an item. If you want to create a new list based on an existing list and make a change, you can use a list comprehension.
You may decide that you want to change a value in a list. Suppose you’re building a menu for a restaurant. You may notice that you have misspelled one of the menu items. To fix this mistake, you will need to change an existing element in the list.
Python Replace Item in List
You can replace an item in a Python list using a for loop, list indexing, or a list comprehension. The first two methods modify an existing list whereas a list comprehension creates a new list with the specified changes.
Let’s summarize each method:
- List indexing: We use the index number of a list item to modify the value associated with that item. The equals sign is used to change a value in a list.
- List comprehension: The list comprehension syntax creates a new list from an existing one. You can specify conditions in your list comprehension to determine the values in the new list.
- For Loop: The loop iterates over the items in a list. You use indexing to make the actual change to the list. We use the enumerate() method to create two lists of index numbers and values over which we can iterate.
In this guide, we walk through each of these methods. We’ll refer to an example of each to help you get started.
Python Replace Item in List: Using List Indexing
The easiest way to replace an item in a list is to use the Python indexing syntax. Indexing allows you to choose an element or range of elements in a list. With the assignment operator, you can change a value at a given position in a list.
We’re building a program that stores information on prices at a clothing store. The price of the first item in our list should be increased by $5. To do this, we use list indexing.
Let’s start by creating a list which contains our product prices:
We use indexing to select and change the first item in our list, 99.95. This value has the index position zero. This is because lists are indexed starting from zero:
Our code selects the item at position zero and sets its value to 104.95. This is a $5 increase on the old value. Our code returns our list of items with the first price changed:
We can change our list by adding five to the current value of prices:
prices corresponds with the first item in our list (the one at index position 0).
Our code returns a list with the same values as our first example:
Python Replace Item in List: Using a List Comprehension
A Python list comprehension may be the most Pythonic way of finding and replacing an item in a list. This method is useful if you want to create a new list based on the values of an existing one.
Using a list comprehension lets you iterate through items in an existing list and create a new list based on a certain criterion. You can generate a new list that only contains items beginning with “C” from an existing list, for instance.
Here, we build a program that calculates a 10% discount on all the products in a clothing store that are worth more than $50. We use our list of product prices from earlier:
Next, we define a list comprehension to replace the items in our list:
This list comprehension iterates through the “prices” list and searches for values worth more than $50. A discount of 10% is applied to those items. We round the discounted values to two decimal places using the round() method.
Our code returns our list of new prices:
A 10% discount has been successfully applied to every item.
Python Replace Item in List: Using a For Loop
You can replace items in a list using a Python for loop. To do so, we need to the Python enumerate() function. This function returns two lists: the index numbers in a list and the values in a list. We iterate over these two lists with a single for loop.
In this example, we’re going to use the same list of prices in our code:
We then define a for loop that iterates over this list with the enumerate() function:
The value “index” stores the index position of an item. “Item” is the value that correlates with that index position. The comma separates the two list values returned by the enumerate() method.
Retrieving two or more values from a method or another value is called unpacking. We have “unpacked” two lists from the enumerate() method.
We use the same formula from earlier to calculate a 10% discount on items worth over $50. Let’s run our code and see what happens:
Our code successfully changes the items in our “prices” list based on our discount.
«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»
Venus, Software Engineer at Rockbot
Find Your Bootcamp Match
You can replace items in a Python list using list indexing, a list comprehension, or a for loop.
If you want to replace one value in a list, the indexing syntax is most appropriate. To replace multiple items in a list that meet a criterion, using a list comprehension is a good solution. While for loops are functional, they are less Pythonic than list comprehensions.
Are you interested in more resources to help you learn Python? If so, you should check out our How to Learn Python guide. This guide contains a list of top courses, books, and learning resources that will help you master the language.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.