Loop through a list with an index in Python
This post will discuss how to loop through a list with an index in Python.
1. Using enumerate() function
The Pythonic solution to loop through the index of a list uses the built-in function enumerate(). The function was introduced in Python 2.3 to specifically solve the loop counter problem. You can use it as follows:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': chars = ['A', 'B', 'C'] for index, value in enumerate(chars): print((index, value)) |
2. Using range() function
Another way to iterate over the indices of a list can be done by combining range() and len() as follows:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': chars = ['A', 'B', 'C'] for i in range(len(chars)): print((i, chars[i])) |
3. Using zip() function
Another preferred solution is to use the zip() function, which returns an iterator of tuples that bundle elements together from each of the sequences. The zip() function solves the problem of looping over multiple sequences. Here’s an example of its usage:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': chars = ['A', 'B', 'C'] for x in zip(range(len(chars)), chars): print(x) |
4. Using map() function
Finally, you have the map() function, which applies a function to every item of sequence and yield the results. Here’s a working example:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': chars = ['A', 'B', 'C'] result = map(lambda x: (x, chars[x]), range(len(chars))) print(list(result)) |
That’s all about looping through a list with an index 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 :)