Skip to content
Advertisement

Python – Write all tuples of a combination using list comprehension

I would like to create all pairs (i, j) such that i goes from 0 to n-1 and j goes from i to n-1. Basically these are all the unique combinations for two lists of length n.

As an example if n=3 then I would like to get

JavaScript

It would be great if I could do this with a list comprehension. The long way around would be

JavaScript

I have tried this list comprehension, unsuccessfully

JavaScript

Advertisement

Answer

Just switch the order of your loops:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement