close

How to start from second index for for-loop

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to start from second index for for-loop in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to start from second index for for-loop?

  1. How to start from second index for for-loop?

    You can iterate throught the list except using the range function to get the indexes of the items you want or slices to get the elements.

  2. start from second index for for-loop

    You can iterate throught the list except using the range function to get the indexes of the items you want or slices to get the elements.

Method 1

First thing is to remember that python uses zero indexing.

You can iterate throught the list except using the range function to get the indexes of the items you want or slices to get the elements.

What I think is becoming confusing here is that in your example, the values and the indexes are the same so to clarify I’ll use this list as example:

I = ['a', 'b', 'c', 'd', 'e']
nI = len(I) # 5

The range function will allow you to iterate through the indexes:

for i in range(1, nI):
    print(i)
# Prints:
# 1
# 2
# 3
# 4

If you want to access the values using the range function you should do it like this:

for index in range(1, nI):
    i = I[index]
    print(i)
# Prints:
# b
# c
# d
# e

You can also use array slicing to do that and you don’t even need nI. Array slicing returns a new array with your slice.
The slice is done with the_list_reference[start:end:steps] where all three parameters are optional and:
start is the index of the first to be included in the slice
end is the index of the first element to be excluded from the slice
steps is how many steps for each next index starting from (as expected) the start (if steps is 2 and start with 1 it gets every odd index).
Example:

for i in I[1:]:
    print(i)
# Prints:
# b
# c
# d
# e

Method 2

You can simply use slicing:

for item in I[1:]:
    print(item)

And if you want indexing, use pythonic-style enumerate:

START = 1
for index, item in enumerate(I[START:], START):
    print(item, index)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read