0

I have a list and I want all possible combinations of items of a list.

from itertools import combinations
l = [1,2,3]
for i in combinations(l,2):
    print(i) // (1, 2) (1,3) (2,3)

I want the same output but without using the itertools. I tried:

l = [1,2,3]
for i in l:
    for j in l:
        print((i,j)) // (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)

How can I get the same output without using itertools?

Tobias Wilfert
  • 919
  • 3
  • 14
  • 26
  • 1
    Possible duplicate of [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Tobias Wilfert Dec 13 '18 at 08:51

3 Answers3

1

Maybe try this

l = [1, 2, 3]
for i in l:
    for j in l:
        if(j <= i):
            continue
        else:
            print(i, j)
Vinay Bharadhwaj
  • 165
  • 1
  • 17
1

You can find sample implementation of itertools.combinations in docs:

Roughly equivalent to:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
Community
  • 1
  • 1
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
0

You can do this in a one liner just for efficiency:

l = [1, 2, 3]

([print(i, j) for i in l for j in l])
caterpree
  • 591
  • 2
  • 7