Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start from second index for for-loop

I have this for-loop. I want i in range(nI) to start from the second number in the I list. Could you guide me?

I=[0,1,2,3,4,5,6]
nI=len(I)
for i in range(nI):
    sum=0
    for v in range(nV):
        for j in range(nJ):
            sum=sum+x1[i][j][v]
return sum
like image 918
Abi Avatar asked Dec 04 '18 21:12

Abi


People also ask

How do I start an index at 1 in Python?

Start index at 1 with enumerate() If you want to start from another number, pass the number to the second argument of enumerate() . For example, this is useful when generating sequential number strings starting from 1.

Do Python for loops start at 0?

For Loops using range() start states the integer value at which the sequence begins, if this is not included then start begins at 0.


1 Answers

If you want to iterate through a list from a second item, just use range(1, nI) (if nI is the length of the list or so).

for i in range(1, nI):
    sum=0
    for v in range(nV):
        for j in range(nJ):
            sum=sum+x1[i][j][v]

Probaly, a part of your function just lost somewhere, but anyway, in in general range() works like this:

range(start_from, stop_at, step_size)

i. e.

for i in range(2, 7, 2):
    print(i, end=' ')

Out:
2 4 6

Edit

Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc.

By default, range starts from 0 and stops at the value of the passed parameter minus one. If there's an explicit start, iteration starts from it's value. If there's a step, it continues while range returns values lesser than stop value.

for i in range(1, 7, 2):
    print(i, end=' ')

Out: 
1 3 5  # there's no 7!

Detailed description of range build-in is here.

like image 181
Mikhail Stepanov Avatar answered Oct 13 '22 09:10

Mikhail Stepanov