Table of Contents
In this example, you will learn to access the index of a list using a for loop.
To understand this example, you should have the knowledge of the following Python programming topics:
- Python for Loop
- Python List
- Python enumerate()
1. Example 1: Using enumerate
my_list = [21, 44, 35, 11] for index, val in enumerate(my_list): print(index, val)
Output
0 21 1 44 2 35 3 11
Using enumerate()
, we can print both the index and the values.
- Pass two loop variables
index
andval
in the for loop. You can give any name to these variables. - Print the required variables inside the for loop block.
The function of enumerate()
is to add a counter (i.e. index
) to the iterate and return it. If you want to learn more about enumerate()
, please visit Python enumerate().
2. Example 2: Start the indexing with non zero value
my_list = [21, 44, 35, 11] for index, val in enumerate(my_list, start=1): print(index, val)
Output
1 21 2 44 3 35 4 11
The value of the parameter start
provides the starting index.
3. Example 3: Without using enumerate()
my_list = [21, 44, 35, 11] for index in range(len(my_list)): value = my_list[index] print(index, value)
Output
0 21 1 44 2 35 3 11
You can access the index even without using enumerate()
.
- Using a for loop, iterate through the length of
my_list
. Loop variableindex
starts from 0 in this case. - In each iteration, get the value of the list at the current
index
using the statementvalue = my_list[index]
. - Print the
value
andindex
.
Related posts:
Python Program to Find the Size (Resolution) of a Image
Python __import__()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Safely Create a Nested Directory
Python Program to Create a Countdown Timer
Python String splitlines()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Find the Factorial of a Number
Python String isspace()
Python globals()
Python Program to Get Line Count of a File
Python Program to Find ASCII Value of Character
Python String isidentifier()
Python Program to Check if a Key is Already Present in a Dictionary
Python type()
Python str()
Python Program to Return Multiple Values From a Function
Python Program to Check If a List is Empty
Python ascii()
Python Program to Find Armstrong Number in an Interval
Python delattr()
Python Program to Convert String to Datetime
Python int()
Python classmethod()
Python String lower()
Python String isdigit()
Python Set remove()
Python String upper()
Python Program to Remove Duplicate Element From a List
Python String islower()
Python String rstrip()
Python strptime()