Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Iterating Over Indexes | Loops
Introduction to Python (copy)
course content

Kursusindhold

Introduction to Python (copy)

Introduction to Python (copy)

1. Getting Started
2. Variables and Types
3. Conditional Statements
4. Other Data Types
5. Loops
6. Functions

book
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
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

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

Opgave

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 and shipment_received are lists of lists, each containing a product name and its quantity.
  • Use a for loop with range() and len() to iterate through the indices of stock_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

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 5. Kapitel 4
toggle bottom row

book
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
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

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

Opgave

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 and shipment_received are lists of lists, each containing a product name and its quantity.
  • Use a for loop with range() and len() to iterate through the indices of stock_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

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 5. Kapitel 4
Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Vi beklager, at noget gik galt. Hvad skete der?
some-alt