Change list items python

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.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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.

Читайте также:  Read config files in java

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:

prices = [99.95, 72.50, 30.00, 29.95, 55.00]

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:

prices[0] = 104.95 print(prices)

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[0]:

prices[0] = prices[0] + 5 print(prices)

prices[0] 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:

prices = [99.95, 72.50, 30.00, 29.95, 55.00]

Next, we define a list comprehension to replace the items in our list:

new_prices = [round(price - (price * 10 / 100), 2) if price > 50 else price for price in prices] print(new_prices)

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:

prices = [99.95, 72.50, 30.00, 29.95, 55.00]

We then define a for loop that iterates over this list with the enumerate() function:

for index, item in enumerate(prices): if item > 50: prices[index] = round(prices[index] - (prices[index] * 10 / 100), 2) print(prices)

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.

Venus profile photo

«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

Conclusion

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.

Источник

Python — Change List Items

To change the value of a specific item, refer to the index number:

Example

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:

Example

Change the values «banana» and «cherry» with the values «blackcurrant» and «watermelon»:

thislist = [«apple», «banana», «cherry», «orange», «kiwi», «mango»]
thislist[1:3] = [«blackcurrant», «watermelon»]
print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Example

Change the second value by replacing it with two new values:

thislist = [«apple», «banana», «cherry»]thislist[1:2] = [«blackcurrant», «watermelon»]print(thislist)

Note: The length of the list will change when the number of items inserted does not match the number of items replaced.

If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Example

Change the second and third value by replacing it with one value:

Insert Items

To insert a new list item, without replacing any of the existing values, we can use the insert() method.

The insert() method inserts an item at the specified index:

Example

Insert «watermelon» as the third item:

Note: As a result of the example above, the list will now contain 4 items.

Источник

How to Modify an Item Within a List in Python

Data to Fish

If so, you’ll see the steps to accomplish this goal using a simple example.

Steps to Modify an Item Within a List in Python

Step 1: Create a List

To start, create a list in Python. For demonstration purposes, the following list of names will be created:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] print(Names)

Run the code in Python, and you’ll get this list:

['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] 

Step 2: Modify an Item within the list

You can modify an item within a list in Python by referring to the item’s index.

What does it mean an “item’s index”?

Each item within a list has an index number associated with that item (starting from zero). So the first item has an index of 0, the second item has an index of 1, the third item has an index of 2, and so on.

  • The first item in the list is ‘Jon.’ This item has an index of 0
  • ‘Bill’ has an index of 1
  • ‘Maria’ has an index of 2
  • ‘Jenny’ has an index of 3
  • ‘Jack’ has an index of 4

Let’s say that you want to change the third item in the list from ‘Maria’ to ‘Mona.’ In that case, the third item in the list has an index of 2.

You can then use this template to modify an item within a list in Python:

ListName[Index of the item to be modified] = New value for the item

And for our example, you’ll need to add this syntax:

So the complete Python code to change the third item from Maria to Mona is:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] #modify Names[2] = 'Mona' print(Names)

When you run the code, you’ll get the modified list with the new name:

Change Multiple Items Within a List

What if you want to change multiple items within your list?

For example, what if you want to change the last 3 names in the original list:

You can then specify the range of index values where the changes are required. For our example, the range of index values where changes are required is 2:5. So here is the code to change the last 3 names in the list:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] #modify Names[2:5] = 'Mona','Lina','Mark' print(Names)

You’ll now see the updated list with the 3 new names:

You can get the same same results by using Names[-3:] as below:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] #modify Names[-3:] = 'Mona','Lina','Mark' print(Names)

And as before, you’ll now see the updated list with the 3 new names:

Источник

Оцените статью