How to Access Index using for Loop - Python
Last Updated :
23 Jul, 2025
When iterating through a list, string, or array in Python, it's often useful to access both the element and its index at the same time. Python offers several simple ways to achieve this within a for loop. In this article, we'll explore different methods to access indices while looping over a sequence:
Using range() and len()
One basic way to access the index while looping is by combining range() with len(). This allows you to manually retrieve elements by index.
Python
data = "GEEKFORGEEKS"
print("Ind and ele:")
for i in range(len(data)):
print(i, data[i])
OutputInd and ele:
0 G
1 E
2 E
3 K
4 F
5 O
6 R
7 G
8 E
9 E
10 K
11 S
Explanation: range(len(data)) generates index numbers. data[i] fetches the character at each index.
Using enumerate()
The enumerate() function returns both the index and the value during iteration, making the loop cleaner and more Pythonic.
Python
data = ["java", "python", "HTML", "PHP"]
print("Ind and ele:")
for i, val in enumerate(data):
print(i, val)
OutputInd and ele:
0 java
1 python
2 HTML
3 PHP
Explanation: enumerate(data) yields (index, value) pairs automatically. No need to manually calculate the index.
Using List Comprehension
List comprehension can also be used to access or generate indices and values separately in a compact way.
Python
data = ["java", "python", "HTML", "PHP"]
print("Indices:", [i for i in range(len(data))])
print("Elements:", [data[i] for i in range(len(data))])
OutputIndices: [0, 1, 2, 3]
Elements: ['java', 'python', 'HTML', 'PHP']
Explanation: [i for i in range(len(data))] creates a list of indices. [data[i] for i in range(len(data))] creates a list of values by index.
Using zip()
The zip() function can combine two lists: one with indices and one with elements, allowing simultaneous iteration.
Python
idx = [0, 1, 2, 3]
data = ["java", "python", "HTML", "PHP"]
print("Ind and ele:")
for i, val in zip(idx, data):
print(i, val)
OutputInd and ele:
0 java
1 python
2 HTML
3 PHP
Explanation: zip(idx, data) pairs each index with its corresponding element. Useful when you already have a list of indices.
Related articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice