banner



How To Change A Value In A List In Python

In that location are three means to supervene upon an item in a Python list. You tin use list indexing or a for loop to supercede an item. If you lot desire to create a new listing based on an existing list and brand a change, you can use a listing comprehension.

You lot may decide that you desire to alter a value in a list. Suppose yous're building a carte for a restaurant. You may detect that y'all accept misspelled ane of the menu items. To fix this error, you will demand to change an existing chemical element in the listing.

Python Replace Detail in List

You can replace an detail in a Python list using a for loop, list indexing, or a listing comprehension. The starting time ii methods alter an existing list whereas a list comprehension creates a new list with the specified changes.

Permit'south summarize each method:

  • Listing 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 listing.
  • List comprehension: The list comprehension syntax creates a new list from an existing one. You can specify weather condition in your listing comprehension to determine the values in the new list.
  • For Loop: The loop iterates over the items in a list. Y'all use indexing to make the actual change to the listing. Nosotros 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 case of each to help you get started.

Python Supersede Item in List: Using List Indexing

The easiest fashion to replace an item in a listing is to use the Python indexing syntax. Indexing allows yous to choose an element or range of elements in a list. With the consignment operator, you lot can change a value at a given position in a list.

Nosotros're edifice a program that stores information on prices at a clothing store. The price of the first item in our list should be increased by $five. To do this, we apply list indexing.

Let's get-go by creating a listing which contains our product prices:

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

The average bootcamp grad spent less than half-dozen months in career transition, from starting a bootcamp to finding their commencement job.

prices = [99.95, 72.50, thirty.00, 29.95, 55.00]

Nosotros use indexing to select and modify the first detail in our list, 99.95. This value has the index position zero. This is considering lists are indexed starting from zero:

prices[0] = 104.95 print(prices)

Our lawmaking selects the item at position zero and sets its value to 104.95. This is a $5 increase on the quondam value. Our code returns our list of items with the get-go price changed:

[104.95, 72.5, xxx.0, 29.95, 55.0]

Nosotros tin change our listing by adding v to the electric current value of prices[0]:

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

prices[0] corresponds with the first item in our list (the one at index position ).

Our code returns a listing with the same values every bit our starting time case:

[104.95, 72.five, 30.0, 29.95, 55.0]

Python Supercede Item in Listing: Using a List Comprehension

A Python list comprehension may be the most Pythonic style of finding and replacing an item in a listing. This method is useful if you want to create a new listing based on the values of an existing one.

Using a listing comprehension lets you iterate through items in an existing list and create a new list based on a sure criterion. You tin generate a new list that only contains items outset with "C" from an existing list, for instance.

form-submission

Observe Your Bootcamp Match

  • Career Karma matches you with elevation tech bootcamps
  • Get exclusive scholarships and prep courses

Hither, we build a programme that calculates a 10% discount on all the products in a clothing shop that are worth more than $50. We utilize our list of production prices from earlier:

prices = [99.95, 72.fifty, 30.00, 29.95, 55.00]

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

new_prices = [round(price - (cost * 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 than $fifty. A discount of 10% is applied to those items. We round the discounted values to ii decimal places using the circular() method.

Our lawmaking returns our list of new prices:

[89.95, 65.25, xxx.0, 29.95, 49.5]

A ten% discount has been successfully applied to every detail.

Python Replace Item in List: Using a For Loop

You can replace items in a listing using a Python for loop. To do so, we need to the Python enumerate() function. This function returns two lists: the alphabetize numbers in a list and the values in a list. We iterate over these 2 lists with a single for loop.

In this example, we're going to utilise the aforementioned list of prices in our lawmaking:

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, detail in enumerate(prices): 	if detail > 50: 		prices[index] = round(prices[index] - (prices[index] * 10 / 100), two)  print(prices)

The value "alphabetize" stores the index position of an item. "Detail" is the value that correlates with that index position. The comma separates the two list values returned by the enumerate() method.

Retrieving ii or more values from a method or another value is chosen unpacking. We have "unpacked" two lists from the enumerate() method.

We apply the same formula from earlier to summate a x% disbelieve on items worth over $50. Allow's run our code and see what happens:

Venus profile photo

"Career Karma entered my life when I needed it almost and speedily 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

[89.95, 65.25, thirty.0, 29.95, 49.v]

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

Decision

You can supervene upon items in a Python list using list indexing, a list comprehension, or a for loop.

If you want to supplant 1 value in a list, the indexing syntax is most advisable. To replace multiple items in a list that meet a benchmark, 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 assistance yous larn Python? If so, you should check out our How to Learn Python guide. This guide contains a listing of top courses, books, and learning resources that will help you lot main the language.

Source: https://careerkarma.com/blog/python-replace-item-in-list/

Posted by: swihartthits1936.blogspot.com

0 Response to "How To Change A Value In A List In Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel