Rit Chatterjee
Rit Chatterjee

Reputation: 13

Automation of .append function in python 3.7

I have a list with nested lists of different lengths ranging from 3 to 105. I want to create based on that new lists that contain a combination of all pairs in these original list following the format: from [7,5,6] to [7,5], [7,6], [5,6]

I used the code below, but this is not feasible with 105 values in a list. Is there an algorithm that can automate this process?

list3 = ([7,5,6], [6,9,7], [7,8,4], [2,4,6,7,9])
list4 = []
for sublist in list3:
    if len(sublist) == 3:
       list4.append([sublist[0], sublist[1])
       list4.append([sublist[0], sublist[2])
       list4.append([sublist[1], sublist[2])

Upvotes: 1

Views: 124

Answers (1)

rayryeng
rayryeng

Reputation: 104515

You could perhaps use itertools.combinations() to help generate unique sets of pairs given a maximum range.

Something like:

from itertools import combinations
list3 = ([7,5,6], [6,9,7], [7,8,4], [2,4,6,7,9])
list4 = []
for sublist in list3:
    for (i, j) in combinations(range(len(sublist)), 2):
       list4.append([sublist[i], sublist[j]])

To make this more efficient, I would recommend using a list comprehension:

list4 = [[sublist[i], sublist[j]] for sublist in list3 for (i, j) in combinations(range(len(sublist)), 2)]

More on list comprehensions versus appending to lists using for loops here: Why is a list comprehension so much faster than appending to a list?


As noted by @chepner in his comment below, combinations takes in any iterable, so you can simply use that as input into combinations. We also don't need to append individual elements. We can generate the combinations we need which will generate a list, and we can just concatenate everything together:

list4 = [t for sublist in list3 for t in combinations(sublist, 2)]

Upvotes: 1

Related Questions