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
indexandvalin 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 variableindexstarts from 0 in this case. - In each iteration, get the value of the list at the current
indexusing the statementvalue = my_list[index]. - Print the
valueandindex.
Related posts:
Python Program to Convert Bytes to a String
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Count the Number of Digits Present In a Number
Python Program to Parse a String to a Float or Int
Python Program to Display Fibonacci Sequence Using Recursion
Python Set update()
Python next()
Python @property decorator
Python List index()
Python Machine Learning - Sebastian Raschka
Python String upper()
Python Program to Create Pyramid Patterns
Python Program to Sort a Dictionary by Value
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python map()
Python hash()
APIs in Node.js vs Python - A Comparison
Python compile()
Python Program to Add Two Numbers
Python Dictionary clear()
Python Operators
Python Program to Check if a Number is Positive, Negative or 0
Python Set intersection_update()
Python String join()
Python isinstance()
Python Program to Catch Multiple Exceptions in One Line
Python Dictionary values()
Python File I/O Operation
Python Program to Find Armstrong Number in an Interval
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python ascii()