Looping with Index📝

Looping with index means going through each item in a list while also knowing the position (index) of each item.

Basic Overview:

When looping through a list with an index, you’re iterating over the list while keeping track of both the position (index) and the value (item) at that position. This approach is particularly helpful when you need to perform operations based on the position of elements in the list, such as comparing, updating, or displaying items.

  • Index: The position of an element in the list.
  • Value: The actual item in the list at that position.

You can use range(len(list)) to generate a sequence of numbers that represent the positions (indexes) of the list items.

list = [4, 6, 7, 2]

for i in range(len(list)):  # Loop through each index
    print('Index: ' + str(i + 1))  # Print the index, starting from 1
    print('Element: ' + str(list[i]))  # Print the element at that index

Index: 1
Element: 4
Index: 2
Element: 6
Index: 3
Element: 7
Index: 4
Element: 2

What’s Happening:

  • In this lesson, we are looping through a list and using the index to keep track of both the position and the value of each element.
  • Python lists are zero-indexed, meaning the first element starts at index 0. However, if you want to start counting from 1, you can adjust the index by adding 1.
  • The range(len(list)) function generates the list’s index numbers, and inside the loop, each index is used to access the corresponding value in the list.
  • This method is useful when you need to know both the position and the value of each item, such as for updating or comparing elements based on their index.

Practice Problem

  • Here, there are four names in a list. Write code so that when the code runs, the index will be listed and the element (names) will be written under it.
# List of names
names = ["Alice", "Bob", "Charlie", "Diana"]

# Write a loop to print the index and name at that index

Answer✅

names = ["Alice", "Bob", "Charlie", "Diana"]

# Write a loop to print the index and name at that index

for i in range(len(names)):  # Loop through each index
    print('Index: ' + str(i + 1))  # Print the index, starting from 1
    print('names: ' + str(names[i]))  # Print the element at that index

Additional Notes:

  • Indexing in Python: Python lists are zero-indexed, meaning the first element has an index of 0. If you want the index to start from 1, you can adjust it by adding 1 during printing.
  • Useful for Tracking: Looping with index is useful in situations where you need to track the position of elements, especially when performing comparisons or updates based on their position.