Iterating Over Indexes
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
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)
Note
The formula
prices[cost] -= prices[cost] * discount_factoris equivalent toprices[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 + 1in the print statement adjusts the index so that it appears to start from1instead of0, 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.
Swipe to start coding
Discount by Position
Apply discount percentages to product prices based on their position in the list using index iteration.
- Use a for loop with
range()andlen()to iterate through the indices ofprices. - Apply discounts based on index position: 10% for index 0, 20% for index 1, 15% for index 2, and 5% for index 3.
- Update each price in the
priceslist by multiplying by the discount factor (e.g., 0.9 for 10% off). - Print
Updated price for item {index}: ${updated_price:.2f}for each item.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain why using `range(len(list))` is better for modifying list elements?
How would I apply a different discount to each item in the list?
What happens if I use a regular `for item in list:` loop instead?
Awesome!
Completion rate improved to 2.17
Iterating Over Indexes
Swipe to show menu
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
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)
Note
The formula
prices[cost] -= prices[cost] * discount_factoris equivalent toprices[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 + 1in the print statement adjusts the index so that it appears to start from1instead of0, 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.
Swipe to start coding
Discount by Position
Apply discount percentages to product prices based on their position in the list using index iteration.
- Use a for loop with
range()andlen()to iterate through the indices ofprices. - Apply discounts based on index position: 10% for index 0, 20% for index 1, 15% for index 2, and 5% for index 3.
- Update each price in the
priceslist by multiplying by the discount factor (e.g., 0.9 for 10% off). - Print
Updated price for item {index}: ${updated_price:.2f}for each item.
Solution
Thanks for your feedback!
single