Satyam Raha Satyam Raha - 15 days ago 6
Python Question

How to combine a list in Python with itself?

I have a list

L=[['g1','g2'],['g3'],['g4','g5','g6']]


now I want

L*L=[['g1','g2','g3'],['g1','g2','g4','g5','g6'],['g3','g4','g5','g6']]


How do I do it in Python 3.5

Answer

You want two things

  • itertools.combinations(L, 2) to get all pairs of sublists in your list
  • combine each pair to make a new list

To sum up

import itertools
LL = [a + b for a, b in itertools.combinations(L, 2)]
Comments