I try to avoid nested loops in Python. In general, I manage to do so by using some itertools utility, the zip function, etc. However, there is still one case for which I have not been able to eliminate the classic nested loop structure: the case where, while iterating through a list, you want to append elements to that same list, and you want those elements to be part of the loop.
Here is an example:
a = [1,5,21]
for i1, val1 in enumerate(a):
for i2 in range(i1+1, len(a)):
val2 = a[i2]
if (val1+val2)%3==0 and abs(val1-val2)<30:
a.append(val1+val2)
print("final", a) #[1, 5, 21, 6, 27, 33, 60, 93]
Can someone help me rewrite this without using a nested loop?