This post will discuss how to traverse a list with indices in Python without modifying the original list.

The standard version of for-loop only prints the items in the list, but not their indices. Sometimes, we may want to access both the items and their indices in the list. There are several ways to do achieve that:

1. Using enumerate() function

The enumerate() function is a built-in function that returns an iterator yielding pairs of index and item from a given iterable. We can use this function to traverse a list with indices by looping over the enumerate object using a for loop. For example:

Download  Run Code

 
The enumerate() function returns an enumerate object that can be converted to other types, such as a list or a dictionary. For example, we can convert the enumerate object to a dictionary that maps each index to its corresponding item like this:

Download  Run Code

2. Using range() function

Another way to iterate a list with indices is to use built-in function range(). It returns a range object, which is an immutable sequence of numbers that can be used to generate indices for looping. We can use this function to traverse a list with indices by looping over the range object and accessing each item by its index. For example:

Download  Run Code

3. Using zip() function

The zip() function is yet another built-in function in Python that takes the iterables to zip together and returns a zip object. The zip object is an iterator that aggregates elements from two or more iterables, such as lists. We can use this function to traverse a list with indices by zipping the list with a range object and looping over the zip object using a for loop. For example:

Download  Run Code

That’s all about traversing a list with indices in Python.