Traverse a list with indices in Python
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
a = [1, 2, 3, 4, 5] for i, v in enumerate(a): print(i, v) ''' Output: 0 1 1 2 2 3 3 4 4 5 ''' |
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:
|
1 2 3 4 5 |
a = [1, 2, 3, 4, 5] # Convert the enumerate object to a dictionary d = dict(enumerate(a)) print(d) # {0: 1, 1: 2, 2: 3, 3: 4, 4: 5} |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
a = [1, 2, 3, 4, 5] for i in range(len(a)): print(i, a[i]) ''' Output: 0 1 1 2 2 3 3 4 4 5 ''' |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
a = [1, 2, 3, 4, 5] for index, item in zip(range(len(a)), a): print(index, item) ''' Output: 0 1 1 2 2 3 3 4 4 5 ''' |
That’s all about traversing a list with indices in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)