frhyme
frhyme

Reputation: 1036

python list all combiniations without itertools

my code

def all_combinations(input_lst):
    return_lst=[]
    for i in range(0, len(input_lst)-1):
        for j in range(i+1, len(input_lst)):
            return_lst.append([input_lst[i], input_lst[j]])
    return return_lst

Upvotes: 0

Views: 690

Answers (2)

Ho0ony
Ho0ony

Reputation: 158

l = [1,2,3,4,]
=> [(2, 1), (3, 1), (4, 1), (3, 2), (4, 2), (4, 3)]

1. use enumerate

[ (x,y) for (i,y) in enumerate(l)  for x in l[i+1:] ]

2. use index

[ (x,y) for y in l  for x in l[l.index(y)+1:] ]

Upvotes: 0

letmutx
letmutx

Reputation: 1416

[(input_lst[i], input_lst[j]) for i in xrange(len(input_lst) - 1) for j in xrange(i + 1, len(input_lst))]

Upvotes: 2

Related Questions