Mike Kehoe
Mike Kehoe

Reputation: 23

Creating sub-lists from a list

I am trying to create a list containing sub-lists in python; like, the proper subset of a set. For example,

A = [1, 2, 3, 4]

Desired List = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4], [1, 2, 3], [1, 2, 4], [2, 3, 4]]

Thanks!

Upvotes: 1

Views: 87

Answers (2)

Francis
Francis

Reputation: 119

It looks like you want to get all the combinations from the list. Try using itertools.combinations

desired_list = itertools.combinations(A, 2)

Upvotes: 1

tzaman
tzaman

Reputation: 47770

Since it seems you only want subsets of size 2 or more:

from itertools import combinations, chain
A = range(1, 5)
list(chain(*(combinations(A, r) for r in range(2, len(A)))))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

If you want all proper subsets, just change range(2, len(A)) to range(len(A)).

Upvotes: 1

Related Questions