Kursusindhold
Introduction to Python (copy)
Introduction to Python (copy)
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
:
# 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:
# 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_factor
is 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 + 1
in the print statement adjusts the index so that it appears to start from1
instead 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
Update inventory levels by combining data from two lists: stock_items
and shipment_received
. Then the result will update the stock_items
list.
- Both
stock_items
andshipment_received
are lists of lists, each containing a product name and its quantity. - Use a
for
loop withrange()
andlen()
to iterate through the indices ofstock_items
. - For each product, add the shipment quantity to the existing stock and update the value in
stock_items
.
Output Requirements
- For each product, print:
Stock updated for <product_name>: <updated_quantity> units
- After all updates, print:
Final stock quantities:
Stock Items: <stock_items>
Løsning
Tak for dine kommentarer!
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
:
# 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:
# 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_factor
is 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 + 1
in the print statement adjusts the index so that it appears to start from1
instead 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
Update inventory levels by combining data from two lists: stock_items
and shipment_received
. Then the result will update the stock_items
list.
- Both
stock_items
andshipment_received
are lists of lists, each containing a product name and its quantity. - Use a
for
loop withrange()
andlen()
to iterate through the indices ofstock_items
. - For each product, add the shipment quantity to the existing stock and update the value in
stock_items
.
Output Requirements
- For each product, print:
Stock updated for <product_name>: <updated_quantity> units
- After all updates, print:
Final stock quantities:
Stock Items: <stock_items>
Løsning
Tak for dine kommentarer!