How to write simultaneous for loop in python for corresponding java syntax

Viewed 24

How to write this simultaneous for loop in python?

Java syntax:

for (int l=0; l<n; l++) {
  for(int x=0, y=x+l; x<n && y<n; x++, y++) {

  }
}

I tried this in Python 3.x:

for x, y in zip(range(n), range(x+l,n))

but I got an error local variable x referenced before assignment.

1 Answers

There are no exact counterpart in Python, but this should be equivalent (and imo more readable). Note that x<n condition is redundant in the Java version anyway:

for l in range(n):
    for y in range(l, n):
        x = y - l
        # The rest of your code
Related