Python for loop index + examples

In this Python tutorial, we will discuss Python for loop index. Here we will also cover the below examples:

  • Python for loop index range
  • Python for loop index and value
  • Python for loop index start at 1
  • Python for loop index start at 0
  • Python for loop index increment
  • Python for loop index decrement
  • Python for loop index out of range
  • Python for loop index backwards
  • Python for loop index dictionary
  • Python for loop index range start at 1
  • Python for loop through dataframe index

Python for loop index

  • Let us see how to check the index in for loop in Python.
  • To check the index in for loop you can use enumerate() function. In Python, the enumerate() is an in-built function that allows us to loop over a list and count the number of elements during an iteration with for loop.
  • There are various method to check how to check the index in for loop in Python.
    • Using range() function
    • Using zip() function
    • Using map() function

Examples:

Let us take an example and check the index in for loop by using enumerate() function.

Source Code:

new_lis = [2, 8, 1, 4, 6]

for x, new_val in enumerate(new_lis):
	print (x, ",",new_val)

Here is the execution of the following given code

Python for loop index
Python for loop index

By using range() function

This is another example to iterate over the range of a list and can perform by the combination of range() and len() function. This function always returns an iterable sequence with the range of numbers.

Here is the Source Code:

my_lis = [6, 1, 9, 2]
 
for new_indic in range(len(my_lis)):
   print(new_indic, my_lis[new_indic])

Here is the Screenshot of the following given code

Python for loop index range function
Python for loop index range function

By using zip function

To do this task we can easily use the function zip(). This method always returns an iterator of tuples where all the values you have passed as a parameter are contained as pairs.

Example:

new_str = ['e', 'f', 'i']
 
for m in zip(range(len(new_str)), new_str):
        print(m)

Implementation:

Python for loop index zip function
Python for loop index zip function

By using map() function

To perform this task we can easily use the map() function in Python. This is a built-in function in Python and it is used to apply a function to all the elements of a sequence.

Example:

new_str2 = ['Germany', 'England', 'France']
 
new_out = map(lambda o: (o, new_str2[o]), range(len(new_str2))) #map function
print(list(new_out))

Here is the execution of the following given code

Python for loop index map function
Python for loop index map function

This is how to check python for loop index

Read: For loop vs while loop in Python

Python for loop index range

  • The range function gives a sequence of integers numbers based on the first and last index given. In this example, the first index is not given by default the index value is set as 0.

Syntax:

for index in range(n):
    statement

In this syntax, the ‘n’ argument is the number of times that the loop will terminate the statement.

Example:

for index in range(2,8):
    print("loop index range",index)

In the above code, we have to use the for loop with the range function and display 6 numbers from 2 to 7.

Python for loop index range
Python for loop index range

Read: Python For Loop

Python for loop index and value

  • Let us see how to access the index of elements in a For loop.
  • In Python, we can assign the next item from an iterable object to the loop on every iteration.

Example:

new_val = ["i", "m", "k"]
new_index = 0

for value in new_val:
   print(new_index, value)
   new_index += 1

In the above code index are an integer number and each iteration of the loop print index as well as value. In this example first, we will declare a variable to store the index and update it on each iteration.

Here is the output of the following given code

Python for loop index and value
Python for loop index and value

Read: Python while loop continue

Python for loop index start at 1

  • In Python to start a for loop at index 1, we can easily skip the first index 0.
  • By using the slicing method [start:] we can easily perform this particular task. In this example, we have to start the index value as 1 and set ‘start’ to be the desired index.
  • By using this operator we can specify that where we have to start the slicing, where to stop, and specify the step.

Example:

my_new_lis = ["Alena", "Joseph", "Mathew"]

for indx in my_new_lis[1:] :
      print(indx)

In the above code, you can see that we have created a list and iterate it through ‘my_new_lis’ starting at index ‘1’.

Here is the execution of the following given code

Python for loop index start at 1
Python for loop index starts at 1

Another example to check how to access a for a loop at index 1

  • If we want to access both the values and the indices of a list then we can use Python in-built function enumerate(). This method adds an index value to an iterable item and returns them combined as an enumerator object.
  • Now let us take an example and check how to use this method.

Source Code:

new_list = ["e","u","o","p","g"]
print("Values in list with index:") 
for new_indices, new_val in enumerate(new_list, start=1): 
    print(list((new_indices, new_val))) 

In the above code first, we will create an enumerator object and convert this object into a list by using the ‘new_list’ as an argument and display the output into each separated list. In this example, we have to set the ‘start’ keyword as an argument and change the indexing value from 0 to 1.

This source code will produce the output:

Python for loop index start at 1
Python for loop index starts at 1

Read: Indexing and slicing in Python

Python for loop index start at 0

  • In Python by default, the range starts from 0 and ends at the value of the passed argument as -1.
  • In this example, we do not iterate items through the list. we would iterate items from len(new_lis) function with the index and then we use this index variable to check the numbers of the list in the sequence of 0..n where n is the last number of the list.

Source Code:

new_lis = ["j","l","q","u","e","t"]

print("index start at:")

for new_indx in range(len(new_lis)):
    print(new_indx, new_lis[new_indx], end = "\n")

Here is the Screenshot of the following given code

Python for loop index start at 0
Python for loop index start at 0

Another example to check how to access a for a loop at index 0

In this example first, we will assign an index value as ‘0’. Now each iteration of the loop print index as well as value from the list.

Example:

my_val = [9,2,3,4,7,8]
new_index = 0

for value in my_val:
   print(new_index, value)
   new_index += 1

Output:

Python for loop index start at 0
Python for loop index start at 0

Read: Python Dictionary index

Python for loop index increment

  • Let us see how to access a for loop at the index increment in Python.
  • By using the range() function we can iterate items through an iterable in steps. This function consists of three parameters start, stop and step. This method will not include the stop value.

Source Code:

new_list = [4,8,10,11,12,16,18]

m = 0
for o in range(len(new_list)):

	if(m >= len(new_list)):
		break
	print(new_list[m], end = "\n ")
	m += 3

In the above code, we will be changing the value of ‘m’ inside the loop and it will change its value as per the given condition ‘m+=3’. In this example, we can use the range function as an argument.

Now it will check the condition if m is greater than 0 (m>0) it will execute the loop with an iterable item.

Output:

Python for loop index increment
Python for loop index increment

Read: Python dictionary comprehension

Python for loop index decrement

  • Let’s take examples and check how to decrement the value in for loop in Python.
  • By using range() function we can perform this task. In Python the range function consists three parameters start, stop, and step and these arguments can help the user to access the decrement value in for loop.
  • In this example first, we will adjust the start, stop and step index value within the for loop and display the output. In range function the start value will always be greater than the stop index value so that the values will automatically decremented.

Here is the Source Code:

for r in range(8,0,-2):
    print('Final result:',r)

In the above code first, we have to put all the values within the range function Inside the parameter set start index value as 8 and the stop index as 0. Now set the step value as -2 which will decrement the value by 2.

Here is the implementation of the following given code

Python for loop index decrement
Python for loop index decrement

Python for loop index out of range

  • In this case when you forget to apply the range () function in for loop then it will raise an error “index out of range”.
  • If you are accessing iterable items in the list and forgot to use range() function then it will raise an error.

Example:

numbers = [1, 5, 3,7]

for date in numbers:
	print(numbers[date])

In the above code first, we will display all the values inside the ‘numbers’ list. The list contains the number of dates. Now we will execute this program.

Execution:

Python for loop index out of range
Python for loop index out of range

Solution:

To solve this problem we can easily use the range() function to iterate items through our list ‘numbers’.

Source Code:

numbers = [1, 5, 3,7]

for date in range(0, len(numbers)):
	print(numbers[date])

In the above code, the range() function creates a list of numbers in a given range. In this example, the range is [1,5,3,7].

Output:

Solution for loop index out of range in Python
Solution for loop index out of range in Python

Read: How to handle indexerror

Python for loop index backwards

  • Let us see how to get reverse order elements in for loop in Python.
  • There are various method to perform this task.
    • By using reversed() function.
    • By using range() function

Examples:

By using reversed() function

To perform the backward iteration we can easily use reversed() function. This method simply selects the elements and displays them in reverse order.

Example:

for m in reversed(range(2, 8)):
        print(m)

Here is the Screenshot of the following given code

Python for loop index backwards
Python for loop index backward

By using range() function

To iterate backward in for loop we can use the range () function with step parameter as -1.

Source Code:

my_lis = ['Australia', 'Germany', 'Indonesia', 'Spain']
for m in range( len(my_lis) - 1, -1, -1) :
   print(my_lis[m])

Implementation:

Python for loop index backwards range function
Python for loop index backward range function

Read: Python dictionary find a key by value

Python for loop index dictionary

To iterate over all key-value pairs of Python dictionary by index we can use the items() function and it returns an iterable sequence.

Source Code:

my_dic = {"a":20,"n":91,"u":87,"t":41}

for new_indx, (new_k, new_val) in enumerate(my_dic.items()):
    print('Index value: ', new_indx, ' :: ', new_k, ':', new_val)

Here is the implementation of the following given code

Python for loop index dictionary
Python for loop index dictionary

Python for loop index range start at 1

  • Here we can see how to start a for loop at index 1 in Python. To solve this problem we can use the range() function.

Syntax:

range(start, stop,[step])

Note: It produces a sequence of integer numbers as per the given condition in arguments.

Example:

for m in range(1,6):
    print(m, end='\n ')

Here is the execution of the following given code

Python for loop index range start at 1
Python for loop index range starts at 1

Read: Python convert dictionary to list

Python for loop through dataframe index

In Python for dataframe, we can use the for statement to iterate items. By using the index attribute of the dataframe we can solve this problem.

Code:

import pandas as pd

student_info = {'stud_name': ['George', 'Potter', 'Adam', 'Gilchrist'],
                'stud_age': [28, 25, 18, 15],
                'stud_str': ['Python', 'Java', 'Sql', 'Mongodb'],
                'stud_id': [192,76,23, 68]}
  
df1 = pd.DataFrame(student_info, columns = ['stud_name', 'stud_age', 'stud_str', 'stud_id'])
  
print("Given Dataframe :\n", df1)
  
print("\nIterate rows by index :\n")
  
for indices in df1.index:
     print(df1['stud_name'][indices], df1['stud_str'][indices])

Here is the screenshot of the following given code

Python for loop through dataframe index
Python for loop through dataframe index

This is how to check python for loop through dataframe.

You may also like the following Python tutorials:

In this Python tutorial, we will discuss Python for loop index. Here we will also cover the below examples:

  • Python for loop index range
  • Python for loop index and value
  • Python for loop index start at 1
  • Python for loop index start at 0
  • Python for loop index increment
  • Python for loop index decrement
  • Python for loop index out of range
  • Python for loop index backwards
  • Python for loop index dictionary
  • Python for loop index range start at 1
  • Python for loop through dataframe index