Change position in list Python

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 youre 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.

Lets 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. Well 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.

» MORE: Python typeerror: > not supported between instances of str and int Solution

Were 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.

Lets start by creating a list which contains our product prices:

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today
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:

[104.95, 72.5, 30.0, 29.95, 55.0]

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 ].

Our code returns a list with the same values as our first example:

[104.95, 72.5, 30.0, 29.95, 55.0]

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.

Find Your Bootcamp Match
  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses
Please enter a valid phone number
Get Matched
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.
» MORE: Python Concatenate Strings: Step-By-Step Guide

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:

[89.95, 65.25, 30.0, 29.95, 49.5]

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, were 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.

» MORE: Python Lambda Functions: An Introduction

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. Lets run our code and see what happens:

"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
[89.95, 65.25, 30.0, 29.95, 49.5]

Our code successfully changes the items in our prices list based on our discount.

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.

Rate this Article


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.


What's Next?

Want to take action?

Get matched with top bootcamps

Want to dive deeper?

Ask a question to our community

Want to explore tech careers?

Take our careers quiz

Video liên quan

Chủ Đề