How to Access Index in Python’s for Loop
Last Updated :
11 Sep, 2023
In this article, we will discuss how to access an index in Python for loop in Python. Here, we will be using 4 different methods of accessing the Python index of a list using for loop, including approaches to finding indexes in Python for strings, lists, etc. Python programming language supports the different types of loops, the loops can be executed in different ways. Loops are one of them, and they’re used for sequential traversal.
Access Index in For Loop With Examples
For instance, traversing in a list, text, or array, there is a “for-in” loop, which is similar to other languages’ “for-each” loop.
We can access the index in Python by using:
Using the index elements to access their values
The index element is used to represent the location of an element in a list. Here we are accessing the index through the list of elements. Here, we are using an iterator variable to iterate through a String.
Python3
data = "GEEKFORGEEKS"
print ( "Indices and Index value in the list:" )
for i in range ( len (data)):
print (i, data[i])
|
Output:
Indices and Index value in the list:
0 G
1 E
2 E
3 K
4 F
5 O
6 R
7 G
8 E
9 E
10 K
11 S
Access Index in Python’s for Loop using enumerate() method
The enumerate() is mostly used for loops where it is used to get the index along with the corresponding element over the given range.
Python3
data = [ "java" , "python" , "HTML" , "PHP" ]
print ( "Indices and values in list:" )
for i in enumerate (data):
print (i)
|
Output:
Indices and values in list:
(0, 'java')
(1, 'python')
(2, 'HTML')
(3, 'PHP')
Access an index using the list comprehension method
List comprehension will make a list of the index and then gives the index and index values.
Python3
data = [ "java" , "python" , "HTML" , "PHP" ]
print ( "Indices in list:" )
print ([i for i in range ( len (data))])
print ( "values in list:" )
print ([data[i] for i in range ( len (data))])
|
Output:
Indices in list:
[0, 1, 2, 3]
values in list:
['java', 'python', 'HTML', 'PHP']
Access an index Using the zip() method
The zip method in Python is used to zip the index and values at a time, we have to pass two lists one list is of index elements and another list is of elements.
Python3
indexlist = [ 0 , 1 , 2 , 3 ]
data = [ "java" , "python" , "HTML" , "PHP" ]
print ( "index and values in list:" )
for index, value in zip (indexlist, data):
print (index, value)
|
Output:
index and values in list:
0 java
1 python
2 HTML
3 PHP
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...