Python For Loop with Index

In this Python tutorial, you will understand Python for loop with index.

I use the for loop with index while iterating over the iterable object to reverse the item of the iterable object. But you can’t access that index using the Python for loop only; you will need to tweak the for loop.

In this tutorial, I have explained how to retrieve the index value of each element in an iterable object-like list.

Let’s start learning,

Python For Loop with Index

You can use the for loop to iterate over iterable objects like lists, tuples, dictionaries, and others. While iterating, you can access each element from the iterable, but you can’t access the index.

The index is the numerical position of the items or the elements in the iterable object, such as a list. Using the index you can access and refer to any element in the iterable object.

However, occasionally, you may need to access the index with an element while looping through the iterable object.

For example, suppose you have a list of numbers like this [3, 4, 6, 7]; if you iterate over this list and access each element using the for loop, you will get the value, not the index, as shown below.

numbers =[3, 4, 6, 7]
for value in numbers:
    print(value)
Python For Loop Without Index

Look at the output; it only prints the actual element from the list, not the index. So in Python, there are multiple ways to access the index of an element in the iterable object, but here I will discuss the most common methods.

READ:  How to convert a tuple to a comma separated string in Python [4 Methods]

Python For Loop Index using enumerate() Function

The enumerate() function in Python takes the iterable object, attaches a counter to it (which is called index), and returns the enumerate objects, which contain both value and their indices.

The syntax is given below.

for index, element in enumerate(iterable, start_idx=0):

Where,

  • iterable: It is the collection (like list, tuple etc) you want to iterate over.
  • index: It is the variable that stores the index of each element within the loop.
  • element: It is the variable that stores the value of each item within the iterable.
  • start_idx=0: It is an optional argument that allows you to specify the starting index.

Let’s see with an example: suppose you need to develop a feature for an e-commerce website where you need to check the availability of a product by its name and return its position in the list; the list is given below.

products = ["laptop", "phone", "camera", "printer"]

Now, you need to search for the element ‘camera’.

search_item = "camera"

Use the code below to find the ‘camera’ and its position (index value in the list).

for index, item in enumerate(products):
    if item == search_item:
        print(f"{search_item} found at position {index}")
        break
Python For Loop With Index

Look at the above picture, which shows that the position (index) of the element ‘camera’ is 2 in the list.

Let’s understand the code part ‘for index, item in enumerate(products):’; this part initializes the for loop and iterates over the list name ‘product’ while iterating. It also uses the enumerate() function to get the element and its corresponding index value.

READ:  Python program for a diamond pattern [2 Methods]

Then, within the for loop, if the statement is specified like this: if item == search_item, it checks if the current item being iterated over is equal to the search_item variable.

If it is equal to search items, then using this line of code ‘print(f”{search_item} found at position {index}”)’, it prints the serach_item and its corresponding index as position. As a result, it returns ‘camera found at position 2’.

This is how you can use the enumerate() function with a for loop to get both the value and corresponding index.

For Loop Python with Index using the range() Function

The range() function in Python allows you to produce a sequence of numbers within the specified range. if you specify the range from 1 to 10, then it generates a number from 1 to 10.

So, here, you will use the concept of range. You will provide the length of the iterable object to the range() function to generate numbers that will act as indexes for each element in the iterable object.

For example, let’s use the same list of ‘products’ that you have created in the above section.

products = ["laptop", "phone", "camera", "printer"]

for index in range(len(products)):
  print("The index value is:",index, "and element is:", products[index])
For Loop Python with Index using the range() Function

Look at the above output. The index of each element is also accessed and printed on the terminal. For example, the index of the item ‘laptop’ is 0, ‘phone’ is 1, and so on.

Let’s understand the code part ‘for index in range(len(products)):’. The range function in Python generates a list of indices that correspond to the items in the “products” list.

  • The for loop iterates over that range of indices and the current index is stored in the variable index for each iteration within the for loop.
  • The element’s value at that index is printed by accessing it from the “products[indx]”  list using the index variable which contains the index value of that element.
READ:  How to Create an Empty Tuple in Python [2 approaches]

Thus you get the element and its corresponding index.

This is how to use the range() function with a for loop to get the index of the element in the iterable object (list).

I hope that from the above two sections, you understand how to get the index of the element in the iterable object using the for loop.

Conclusion

In this Python tutorial, you learned about a Python for loop with index, where you learned how to get the index value of an element or items in an iterable object such as a list.

You learned about two functions, enumerate() and range(), which help you to get the index of the element in the list.

You may like to read: