'how to loop with multiple index in Python
I have to write a loop which is very simple in languages like java and c.
for (int i = 0; i <arr.length()-1; i++) {
for (int j = i+1; j <arr.length(); j++) {
//process
}
}
But I can't get to mimic this in Python. For example:
for number in arr:
print(number)
But how to iterate with the i and j indices.
Solution 1:[1]
ll = len(arr)
for i in range(ll):
for j in range(i+1, ll, 1):
# process
Solution 2:[2]
Use a nested loop, the same as you would in another language:
for i in range(len(arr)-1):
for j in range(i, len(arr))::
print(arr[j])
or:
for i in range(len(arr)-1):
for number in arr[i:]:
print(number)
or perhaps:
for i, n1 in enumerate(arr[:-1]):
for j, n2 in enumerate(arr[i:], i):
print(f"arr[{i}] = {n1}, arr[{j}] = {n2}")
depending on whether your processing needs to operate on the elements themselves, the indices, and/or both.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bugface |
| Solution 2 | Samwise |
