0

In my code below, 'single' refers to a finite list. I then need to get all possible pairs from this list; however, the program didn't finish executing.

After messing around with some print statements, for some reason, despite 'single' having a finite number of elements (13122; I checked with len()) the for loop was running forever, until I but a break statement in which forcibly ends the loop when the index gets too high. Initially I thought this was because I was referencing over 'single' twice; however, even when I replaced 'single' with copy.deepcopy(single), the same problem occurred, and my fix no longer worked.

If it is of any help, the elements of 'single' are themselves lists.

'''

for index1, i in enumerate(single):
    for index2, j in enumerate(single):
        return_list.append([i,j])
        
        if (index1 > length):
            break

'''

riemann_lebesgue
  • 299
  • 5
  • 17
  • List of what? List of lists, tuples? Or just integers or strings? – Vijeth Rai Jul 15 '20 at 14:51
  • 1
    Your two `for` loops will iterate 13122*13122=172186884 times. It's just taking a long time. – jkr Jul 15 '20 at 14:51
  • when I used enumerate to keep track of the index, the first index grew beyond 13122. In any case, I wanted to check some cases numerically for a maths problem and have done so a different way – riemann_lebesgue Jul 15 '20 at 15:20

1 Answers1

0

By iterating through the list twice, you are having to append to that return_list 13122*13122=172186884 times. That will take ages, there are much better and more performant ways of calculating that list if that is really what you want to do (will take up an enormous amount of memory).

Take a look at itertools.combinations.

list(itertools.combinations(single, 2))
Luke Storry
  • 6,032
  • 1
  • 9
  • 22