What is an “Index Loop”?

Index Loop

An index loop iterates, repeats through elements in a collection sequentially, over elements of a sequence while tracking their index (position). This is useful when both the value and its position are needed.

In Python, the enumerate() function creates an index loop, providing both the index and the element.

  • Access elements alongside their index
  • Perform operations based on an element’s position

Example: You can display both the index and the item in a list using an index loop.

Python Index Loop

# List of items
items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]

# Loop through the items list and print each item with its index
for index, item in enumerate(items):
    print(f"Index {index}: {item}")

Index 0: Item 1
Index 1: Item 2
Index 2: Item 3
Index 3: Item 4
Index 4: Item 5

Javascript Index loop

%%javascript

const items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"];

items.forEach((item, index) => {
    console.log(`Index ${index}: ${item}`);
});

<IPython.core.display.Javascript object>

Python Popcorn Hack

# List of tasks
tasks = [
    "Finish homework",
    "Clean the room",
    "Go grocery shopping",
    "Read a book",
    "Exercise"
]

# Function to display tasks with indices
def display_tasks():
    print("Your To-Do List:")
    for index in range(len(tasks)):
        print(f"{index + 1}. {tasks[index]}")  # Display task with its index

# Call the function
display_tasks()

Your To-Do List:
1. Finish homework
2. Clean the room
3. Go grocery shopping
4. Read a book
5. Exercise

Javascript Popcorn Hack

%%javascript
// List of tasks
const tasks = [
    "Finish homework",
    "Clean the room",
    "Go grocery shopping",
    "Read a book",
    "Exercise"
];

// Function to display tasks with indices
function displayTasks() {
    console.log("Your To-Do List:");
    for (let index = 0; index < tasks.length; index++) {
        console.log(`${index + 1}. ${tasks[index]}`); // Display task with its index
    }
}

// Call the function
displayTasks();
<IPython.core.display.Javascript object>

Summary of To-Do List Codes

Both the Python and JavaScript codes display a list of tasks with their indices.

  1. Task List: Define a list of tasks.

  2. Display Function: Create a function that loops through the tasks and prints each one alongside its index.

  3. Function Call: Execute the function to show the list.

How to Create Your Own

To create your own version, follow these steps:

  1. Define Your Tasks: List the tasks you want to include.

  2. Create a Display Function: Write a function that iterates through the tasks and prints them with their indices.

  3. Call the Function: Execute the function to display your tasks.

Using this template, you can easily customize your own to-do list!