Open In App

How to Access Index using for Loop – Python

Last Updated : 29 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

[GFGTABS]
Python

data = "GEEKFORGEEKS"

print("Ind and ele:")

for i in range(len(data)):
    print(i, data[i])


[/GFGTABS]

Output

Ind 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.

[GFGTABS]
Python

data = ["java", "python", "HTML", "PHP"]

print("Ind and ele:")

for i, val in enumerate(data):
    print(i, val)


[/GFGTABS]

Output

Ind 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.

[GFGTABS]
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))])


[/GFGTABS]

Output

Indices: [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.

[GFGTABS]
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)


[/GFGTABS]

Output

Ind 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:



Article Tags :
Practice Tags :

Similar Reads