In this article, we will discuss different ways to print list items along with their index position in Python.
Table Of Contents
Method 1: Using enumerate() function
in this first technique, we are going to use the enumerate() function.
This enumerate() function accepts a sequence as an argument, and yields pair containing the index position and the value for each of the item in the given sequence.
We will pass our list object to the enumerate() function, and iterate over all the pairs returned by this function. Each pair will have the index position and the value at that corresponding index position.
Let’s see an example,
listOfStrs = ['Hello', 'this', 'is', 'a', 'correct', 'way', 'to', 'code'] # print list elements along with index number for index, value in enumerate(listOfStrs): print(index, " :: ", value)
Output:
Frequently Asked:
0 :: Hello 1 :: this 2 :: is 3 :: a 4 :: correct 5 :: way 6 :: to 7 :: code
Method 2: Using for-loop
In this example, we printed all the list elements along with their index positions.
In these technique, first we are going to fetch the length of the list.
Then we are going to iterate from index zero till the length of the list. During iteration, for each index position we will fetch the list element at that index position and print its value along with the index position.
Let’s see an example,
listOfStrs = ['Hello', 'this', 'is', 'a', 'correct', 'way', 'to', 'code'] # print list elements along with index number for i in range(len(listOfStrs)): print(i, " :: ", listOfStrs[i])
Output:
0 :: Hello 1 :: this 2 :: is 3 :: a 4 :: correct 5 :: way 6 :: to 7 :: code
This is the simplest approach. We just used the for loop to iterate over the list elements by index position and printed the index along with the values.
Summary
We learned about two different ways to print list items along with their index positions in Python.