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
x
2
1
[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
2
It would be great if I could do this with a list comprehension. The long way around would be
JavaScript
1
6
1
n = 3
2
tuples = []
3
for i in range(n):
4
for j in range(i, n):
5
tuples.append((i, j))
6
I have tried this list comprehension, unsuccessfully
JavaScript
1
2
1
tuples = [(i,j) for i in range(3) and j in range(i, 3)]
2
Advertisement
Answer
Just switch the order of your loops:
JavaScript
1
2
1
tuples = [(i,j) for i in range(3) for j in range(i, 3)]
2
Output:
JavaScript
1
2
1
Out[425]: [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
2