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.
CodePudding user response:
ll = len(arr)
for i in range(ll):
for j in range(i 1, ll, 1):
# process
CodePudding user response:
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.