Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

n = 3
tuples = []
for i in range(n):
    for j in range(i, n):
         tuples.append((i, j))

I have tried this list comprehension, unsuccessfully

tuples = [(i,j) for i in range(3) and j in range(i, 3)]

>Solution :

Just switch the order of your loops:

tuples = [(i,j) for i in range(3) for j in range(i, 3)] 

Output:

Out[425]: [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading