Python get all combinations of length n

In case you don't want to calculate all the combinations at once, you can make a generator that returns the combinations of length n as follows:

def combinations(list_get_comb, length_combination):
    """ Generator to get all the combinations of some length of the elements of a list.

    :param list_get_comb: List from which it is wanted to get the combination of its elements.
    :param length_combination: Length of the combinations of the elements of list_get_comb.
    :return: Generator with the combinations of this list.
    """

    # Generator to get the combinations of the indices of the list
    def get_indices_combinations(sub_list_indices, max_index):
        """ Generator that returns the combinations of the indices

        :param sub_list_indices: Sub-list from which to generate ALL the possible combinations.
        :param max_index: Maximum index.
        :return:
        """
        if len(sub_list_indices) == 1:  # Last index of the list of indices
            for index in range(sub_list_indices[0], max_index + 1):
                yield [index]
        elif all([sub_list_indices[-i - 1] == max_index - i for i in
                  range(len(sub_list_indices))]):  # The current sublist has reached the end
            yield sub_list_indices
        else:
            for comb in get_indices_combinations(sub_list_indices[1:],
                                                 max_index):  # Get all the possible combinations of the sublist sub_list_indices[1:]
                yield [sub_list_indices[0]] + comb
            # Advance one position and check all possible combinations
            new_sub_list = []
            new_sub_list.extend([sub_list_indices[0] + i + 1 for i in range(len(sub_list_indices))])
            for new_comb in get_indices_combinations(new_sub_list, max_index):
                yield new_comb  # Return all the possible combinations of the new list

    # Start the algorithm:
    sub_list_indices = list(range(length_combination))
    for list_indices in get_indices_combinations(sub_list_indices, len(list_get_comb) - 1):
        yield [list_get_comb[i] for i in list_indices]

By calling:

comb = combinations([1, 2, 3, 4], 3) 

You can calculate one by one each of the possible combinations of length 3 by calling next(comb) or by using the generator in a loop: for c in comb:.

The advantage of this code is that, in case the list is very long, there are many possible combinations and you want to get one of all the possible combinations that meets some criteria, you wouldn't need to calculate all the possible combinations and then filter them by that criteria. You can just generate them one by one until you find a combination that meets your criteria. This will be computationaly much more efficient. As well, note that the above code calculates only those combinations of length n, instead of calculating all the possible combinations and then filtering them by length, which makes it more efficient as well.

However, if wanted, you can calculate all the combinations at once by listing them list(comb).

Listing all combinations of a list up to length n (Python)

Tags: python , list Answers: 1 | Viewed 5,446 times

What would be an efficient algorithm to do the following:
given a list, we have to output all combinations of elements up to a length n. Let's say x = ['a','b','c','d','e'] and n = 2. The output should be:


[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e']]


Stefano Sanfilippo answer at 2014-07-26 10


You could use itertools.combinations and iterate for increasing lengths:


from itertools import combinations
x = ['a','b','c','d','e']
c = []
n = 2
for i in range(n):
c.extend(combinations(x, i + 1))
print(c)

or, using a list comprehension:


from itertools import combinations
x = ['a','b','c','d','e']
n = 2
c = [comb for i in range(n) for comb in combinations(x, i + 1)]
print(c)

* The answers/resolutions are collected from stackoverflow, are licensed under CC BY-SA 3.0

[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e']] 

from itertools import combinations  x = ['a','b','c','d','e'] c = [] n = 2  for i in range(n):
c.extend(combinations(x, i + 1)) print(c)

from itertools import combinations  x = ['a','b','c','d','e'] n = 2 c = [comb for i in range(n) for comb in combinations(x, i + 1)] print(c) 

x = ['a', 'b', 'c', 'd', 'e'] result = []  for length in range(1,3):
result.extend(itertools.combinations(x, length)) print result

[('a',), ('b',), ('c',), ('d',), ('e',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e')] 

>>>
x = ['a','b','c','d','e'] >>>
n = 2 >>>
import itertools >>>
[list(comb) for i in range(1, n+1) for comb in itertools.combinations(x, i)] [['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e']]

x = ['a','b','c','d','e'] n = 2  outList = [] for i in range(0,len(x)):
outEleList = []
outEleList.append(x[i])
outList.append(outEleList)
for c in range(i,len(x)):
out = []
out.append(x[i])
out.append(x[c])
outList.append(out) print outList

How to Get All Combinations of a List in Python - Codingem

5 days ago Import the built-in itertools module.Specify a list of items.Initialize an empty list for storing the combinations.Create a loop that loops values from 0 to the length of the list + 1.Create an inner loop that adds combinations of length r to the list of combinations.

1. Import the built-in itertools module.
2. Specify a list of items.
3. Initialize an empty list for storing the combinations.
4. Create a loop that loops values from 0 to the length of the list + 1.
5. Create an inner loop that adds combinations of length r to the list of combinations.

Show details

See also: List Loops

Python: Combinations of a List (Get All Combinations of a …

1 week ago Sep 20, 2021  · iterable refers to the iterable for which you want to find combinations, r refers to the length of the combinations you want to produce. Now that you know how the …

Show details

Python | Combinations of elements till size N in list

1 week ago Aug 26, 2019  · But sometimes, we require more and we wish to have all the combinations of elements of all sizes till N. Let’s discuss certain ways in which this function can be performed. …

Estimated Reading Time: 40 secs

Show details

See also: List Function

How to Get All Combinations of a List in Python - Codingem

1 week ago So you want no duplicate values in the list of all the combinations? No problem. To obtain the unique powerset in Python, convert the list to a set to remove duplicates. Otherwise, use the same approach as above. Here is how the code looks after the change: Now it only returns the combinations where there are no duplicate values:

Show details

See also: List

How to find all combinations from a list of elements in …

3 days ago 31 rows  · Aug 24, 2022  · Find all combinations of size 2. To find all combinations of size 2, a solution is to use the python module called itertools. from itertools import combinations for i …

Show details

See also: Python List

Python | Combinations of items up to size N in a list

4 days ago Method # 1: Using a comprehension list + combinations () This task can be accomplished using a list comprehension, which can perform the task of changing the length combination () and …

Show details

See also: List

Python program to get all pairwise combinations from a list

4 days ago Feb 21, 2022  · Method 1: Using simple loops. We can access all combinations of the list using two loops to iterate over list indexes. If both the index counters are on the same index value, …

Show details

See also: List Loops

Python program to get all unique combinations of two Lists

1 week ago Jun 16, 2021  · Import itertools package and initialize list_1 and list_2. Create an empty list of ‘unique_combinations’ to store the resulting combinations so obtained. Call itertools.permutations ( ) which will return permutations of list_1 with length of list_2. Generally, the length of the shorter list is taken and if both lists are equal, use either.

Show details

See also: List

Combinations of a List in Python | Delft Stack

5 days ago (10, 5) (10, 'Hi') (5, 'Hi') A sorted list will output the combination tuples in sorted order. A combination of one element in the list with itself is not possible using the combinations() …

Show details

See also: List

How do you get all the combinations of n numbers in Python?

To find all the combinations of a Python list, also known as a powerset, follow these steps:.
Import the built-in itertools module..
Specify a list of items..
Initialize an empty list for storing the combinations..
Create a loop that loops values from 0 to the length of the list + 1..

How do you get all the possible combinations of letters in python?

Practical Data Science using Python.
st_arr := a new list..
for i in range size of s - 1 to 0, decrease by 1, do. for j in range 0 to size of st_arr - 1, do. insert (s[i] concatenate st_arr[j]) at the end of st_arr. insert s[i] at the end of st_arr..
return st_arr..

How do you generate all possible combinations of one list?

To list all combinations possible in an Excel sheet, follow the following procedure;.
Step 1: Open the sheet. You first need to open the sheet with data from which you want to make all possible combinations. ... .
Step 2: Select cell for result. ... .
Step 3: Drag the formula to other cells..

How do you generate all possible combinations of two lists in Python?

How to get all unique combinations of two lists in Python.
list1 = ["a", "b", "c"].
list2 = [1, 2].
all_combinations = [].
list1_permutations = itertools. permutations(list1, len(list2)) ... .
for each_permutation in list1_permutations:.
zipped = zip(each_permutation, list2).
all_combinations. ... .
print(all_combinations).