3

How to start a loop from certain number to n numbers in python.

Example: starting loop from 2 but ending based on n numbers If I start a loop from 2 but wish to go through next 5 numbers how to achieve that?

2 3 4 5 6 7

8
  • 5
    for i in range(start, start+length+1)? Commented Dec 1, 2021 at 18:51
  • 1
    docs.python.org/3/tutorial/controlflow.html#the-range-function Commented Dec 1, 2021 at 18:57
  • @not_speshal, you don't need to add 1 to start+length. Commented Dec 1, 2021 at 19:00
  • 1
    @MarkLavin - Yes you do. list(range(2, 2+5)) is [2, 3, 4, 5, 6]. OP wants the next 5 numbers. Commented Dec 1, 2021 at 19:01
  • setting 'length' to 6 would make more sense though, since that's the desired length.. or calling it something else! Commented Dec 1, 2021 at 19:02

1 Answer 1

5

Range will do that for you

start = 2
length = 6

for i in range(start, start + length):
    print(i)

Or you could get a range from 0 and add your offset onto the number inside the loop

for i in range(length):
    print(i+start)

Which would be less common but depending on the scenario this might be more readable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.