Is there a more rational way to sort through all possible lists of 5 items that are taken (items) from another list? The initial list has a lot of elements (from 100 to 300), so my method is very slow.

for i1 in lst[:-4]: for i2 in lst[lst.index(i1)+1:-3]: for i3 in lst[lst.index(i2)+1:-2]: for i4 in lst[lst.index(i3)+1:-1]: for i5 in lst[lst.index(i4)+1:]: result.append([i1, i2, i3, i4, i5]) 
  • And what if there are 200 - 300 or more, will you write 300 cycles? - And
  • I need to go through one list. That's what I ask for an alternative - Agio

1 answer 1

itertools.combinations(iterable, [r]) - combinations of length r from iterable without duplicate elements.

 >>> print list(itertools.combinations([1,2,3], 2)) [(1, 2), (1, 3), (2, 3)]