How to avoid multiple nested for-loops when one nested for-loop has range up to the current iteration of the outer for-loop? For example, consider the following code: This program returns a triplet from a list arr such that arr[i] - arr[j] = arr[j] - arr[k] = d and i<j<k.

```d =3
arr = [1, 2, 4, 5, 7, 8, 10]
list1 = []

for biggest in range(0, len(arr)):
for bigger in range(0, biggest):
for big in range(0, bigger):
if abs(arr[big] - arr[bigger]) == d and abs(arr[bigger] - arr[biggest]) == d:
list1.append([arr[big], arr[bigger], arr[biggest]])
print(list1))```

Are there any other alternatives to using multiple nested loops?

Sep 10, 2018 in Python 2,990 views

## 1 answer to this question.

You can replace the three loops with:

```from itertools import combinations

for big, bigger, biggest in combinations(range(0, len(arr)), 3):```

You can replace all the code with:

```print([t for t in combinations(arr, 3)
if t[2] - t[1] == t[1] - t[0] == d])```
• 58,090 points
correct me if i'm wrong, but does your code omit the condition big<bigger<biggest?

It prints the value of big, bigger and biggest. In this case, it would be:

`[(1, 4, 7), (2, 5, 8), (4, 7, 10)]`

## Python: nested 'for' loops

Could use itertools: >>> for comb in itertools.combinations_with_replacement(range(9, -1, ...READ MORE

## How can I deal with python eggs for multiple platforms in one location?

Try virtualenv : http://pypi.python.org/pypi/virtualenv This helps you create isolated ...READ MORE

+1 vote

## instead of using two for loops in python

This example might help: for x, y in ((a,b) ...READ MORE

## how do i change string to a list?

suppose you have a string with a ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

## Avoiding multiple nested for-loops in python

You can replace the three loops with: from ...READ MORE