Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Iterating Over Indexes | Section
Python Basics for Data Analysis
Avsnitt 1. Kapitel 28
single

single

bookIterating Over Indexes

Svep för att visa menyn

In the previous task, you provided a specific number of items to the range() function. But what if you need to determine the number dynamically? This is where index iteration becomes essential.

Index iteration is a core technique in Python that allows you to access and modify elements by their positions within data structures like lists or arrays. It's especially helpful for tasks that need precise control over each element, such as updating inventory levels or managing sales data in a grocery store.

Watch as Alex demonstrates how iterating over indexes can simplify operations in our grocery store example:

Iterating over indexes is useful when you need to access both the index and the value of each element in a list. When we use range() with len(), we are combining two functions to generate a sequence of numbers corresponding to the indices of the list elements. This method is particularly useful in loops where you need to access or modify elements based on their position.

For example, this for loop accesses the index and the value of each element in the grocery_list:

12345678
# List of grocery items grocery_list = ["Apples", "Bananas", "Carrots", "Cucumbers"] # Initialize a for loop to iterate over indexes for item in range(len(grocery_list)): print("Index:", item) print("Item:", grocery_list[item]) print("----") # Printing a divider line for clarity
copy

Example Application

To apply a discount to a list of prices, we need to modify the elements of the list directly. Using a simple loop like for cost in prices: would only give us a copy of each item, not a reference to the actual item in the list. Modifications made in this manner would not affect the original list.

To ensure we directly update each element in the prices list, we use range(len(prices)) to iterate over the indices. This allows us to apply a discount factor to each element:

12345678910111213
# List of original prices of grocery items prices = [1.50, 2.00, 0.75, 3.25] # Discount factor (10% off each item) discount_factor = 0.10 # Iterate over the list of prices using range(len()) for cost in range(len(prices)): # Apply the discount by reducing the price prices[cost] -= prices[cost] * discount_factor print(f"New price of item {cost + 1}: ${prices[cost]}") print("Updated prices:", prices)
copy
Note
Note
  • The formula prices[cost] -= prices[cost] * discount_factor is equivalent to prices[cost] = prices[cost] - prices[cost] * discount_factor. This subtracts a portion of the original price (determined by the discount) from itself, effectively applying the discount;
  • The cost + 1 in the print statement adjusts the index so that it appears to start from 1 instead of 0, making it more user-friendly.

This method ensures that the original list prices is updated directly with the new, discounted prices, reflecting the changes immediately across the program wherever the prices list is used.

Uppgift

Swipe to start coding

Discount by Position

Apply discount percentages to product prices based on their position in the list using index iteration.

  1. Use a for loop with range() and len() to iterate through the indices of prices.
  2. Apply discounts based on index position and update each price in the prices list: 10% for index 0, 20% for index 1, 15% for index 2, and 5% for index 3.
  3. Print Updated price for item {index}: ${updated_price:.2f} for each item.

Lösning

Note
Note

.2f formats a number to 2 decimal places (e.g., 55.00). Use it like: updated_price[index]:.2f.

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 28
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt