# 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

### 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

### 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:

### 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

This is how to check python for loop index

## 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 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 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

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 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

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 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 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 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:

### 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:

## 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

### 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 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 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 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

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
{"ft_lang_label":"__label__en","ft_lang_prob":0.6954459,"math_prob":0.9687521,"size":11855,"snap":"2021-31-2021-39","text_gpt3_token_len":2896,"char_repetition_ratio":0.20310523,"word_repetition_ratio":0.21185617,"special_character_ratio":0.25913116,"punctuation_ratio":0.12666667,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9969888,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-09-25T02:42:24Z\",\"WARC-Record-ID\":\"<urn:uuid:c32697a1-df9b-4581-a04c-214ab72df217>\",\"Content-Length\":\"101051\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:0aca9407-87aa-40be-8d50-74e5999d12e4>\",\"WARC-Concurrent-To\":\"<urn:uuid:7baf6f0a-9374-4a5c-b254-f280e0c5aa40>\",\"WARC-IP-Address\":\"172.67.133.165\",\"WARC-Target-URI\":\"https://pythonguides.com/python-for-loop-index/\",\"WARC-Payload-Digest\":\"sha1:UHUQJO4L4XQ7PRNODT6UOU4YVMGDMF6I\",\"WARC-Block-Digest\":\"sha1:GGFJN3HCA7VC42XMU54KN7IV7CTEUMV2\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-39/CC-MAIN-2021-39_segments_1631780057589.14_warc_CC-MAIN-20210925021713-20210925051713-00442.warc.gz\"}"}