A complete guide to replacing list items in Python

by Alex
A complete guide to replacing list items in Python

There are three ways to replace an element in a list in Python. You can do this by referring to the item by index or by looping through the entire list. If you want to create a new list based on an existing list and make changes to it, you can also use list comprehension. In everyday practice, the need to change one or more values in a list arises quite often. Suppose you are creating a menu for a restaurant and notice that you have misdefined one of the items. To fix such an error, you simply need to replace an existing item in the list.

Replacing an item in a list in Python

You can replace an item in a list in Python using the for loop, index reference, or list comprehension. The first two methods modify an existing list, while the latter creates a new list with the specified changes. Let’s briefly describe each method:

  • Index reference: we use the sequence number of the list item to change its value. The equal sign is used to assign a new value to the selected item.
  • List comprehension or list generator creates a new list from an existing list. The list comprehension syntax allows you to add various conditions to define values in a new list.
  • The For loop iterates through the list items. Index reference is used to make changes in this case. We apply the enumerate() method to create two lists: one with indexes and one with the corresponding element values, and iterate over them.

In this tutorial, we will look at each of these methods. For a fuller understanding of the approaches given, we have also prepared examples of how to use each of them.

Replacing an item in a list in Python: Index reference

The easiest way to replace an item in a list is to use the index reference syntax. This allows you to select a single item or a range of consecutive items, and using the assignment operator, you can change the value at a given position in the list. Let’s imagine that we are creating a program that stores information about the prices in a clothing store. The price of the first item in our list must be increased by $2. Let’s start by creating a list that contains the prices of our items:
prices = [29.30, 10.20, 44.00, 5.99, 81.90]
We use index reference to select and modify the first item in our 29.30 list. This value has a zero index. This is because lists are indexed starting from zero.
prices[0] = 31.30
print(prices)
Our code selects the item in the zero position and sets its value to 31.30, which is $2 more than the previous price. Then we return the list with the corrected price of the first item:
[31.30, 10.20, 44.00, 5.99, 81.90]
We can also change our list by adding two to the current value of prices[0]:
prices[0] = prices[0] + 2
print(prices)
prices[0] corresponds to the first element in our list (the one at the zero index position). This code prints the list with the same values as in the first case:
[31.30, 10.20, 44.00, 5.99, 81.90]
Replacing an item in a list in Python: list comprehension Using the list generator in Python may be the most elegant way to find and replace an item in a list.

This method is especially useful if you want to create a new list based on the values of an existing list. Using list comprehension allows you to go through the items in an existing list and form a new list based on a specific criterion. For example, you can compose a new list from a sequence of words by selecting only those that begin with "C". Here we have written a program that calculates a 30% discount on all items in a clothing store that cost more than $40. We use the list of prices of items presented earlier:
prices = [29.30, 10.20, 44.00, 5.99, 81.90]
Next, we apply list comprehension to replace the items in our list:
sale_prices = [round(price - (price * 30 / 100), 2) if price > 40 else price for price in prices]
print(sale_prices)
So, our generator looks through the list of “prices” and searches for values greater than $40. We apply a 30% discount to all found products. We round up the obtained price values with the discount to two decimal places after the point using the round() method. Our code outputs the following list with the new prices:
[29.3, 10.2, 30.8, 5.99, 57.33]

Replacing an item in a list in Python: the for loop

You can change list items using the for loop. To do this, we need the Python function enumerate(). This function returns two lists: a list with index numbers and a list with the values of the corresponding elements. We can iterate over these two sequences as needed with a single for loop. In this example, we will use the same list of prices:
prices = [29.30, 10.20, 44.00, 5.99, 81.90]
Then we define a for loop that goes through this list using the enumerate() function:
for index, item in enumerate(prices):
if item > 40:
prices[index] = round(prices[index] - (prices[index] * 30 / 100), 2)
print(prices)
In the code above the “index” variable contains the item position number. The “item” in turn is the value stored in the list item at that position. The index and the corresponding value returned by the enumerate() method are separated by a comma. Getting two or more values from the tuple returned by this function is called unpacking. We “unpacked” the elements of two lists from the enumerate() method. Here we use the same formula we used earlier to calculate a 30% discount on items over $40. Let’s run our code and see what happens:
[29.3, 10.2, 30.8, 5.99, 57.33]
Our code successfully changes the items in the “prices” list to match our discount.

Conclusion

You can replace items in a list in Python using index reference, list comprehension, or the for loop. If you want to change a single value in a list, index comprehension is most appropriate. For replacing multiple items in a list that satisfy a certain condition, using list comprehension is a good solution. Although for loops are more functional, they are less elegant than list generators.

Related Posts

LEAVE A COMMENT