1

I have the following for loop in C that I want to mimic in Python:

for (index = 0; index < n; ++index)
{
    for (i = 0, j = index; j < n; ++i, ++j)
    {
         'do something'
    }
}

Is there a more elegant/Pythonic way to do this, or do I have to declare a variable outside of the loop like so:

for index in range(m):
    i = 0
    for j in range(index, m):
        'do something'
        i += 1
4
  • 2
    It really depends on what you're doing in that loop. For instance, the loop you describe could be outright replaced by a list comprehension instead. Commented Jan 4, 2016 at 21:12
  • Probably, but it depends what you're doing in your loop. You rarely want to iterate on a range if you mean to use the value as an index. Commented Jan 4, 2016 at 21:12
  • index is just going be used as the bounds of my loop and i and j are going to be the indices to a nested list that I want to populate. Commented Jan 4, 2016 at 21:15
  • What does the nested list that you want to populate look like? Could you add this information to your question? Commented Jan 4, 2016 at 21:17

1 Answer 1

1

It's hard to say without knowing more about what is going in the second loop, but as it's written I would say:

for index in range(n):
    for i,j in enumerate(range(index,n)):
        'do something'

would be the way you'd do that.

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

2 Comments

That appears to be what I was looking for. I didn't realize you can call enumerate() on a range to populate i and j. Thank you.
You can call enumerate on any iterable.

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.