# How to generate python combinations of 4 digits in list of various digits?

42
February 12, 2019, at 11:20 PM

I have a list such as

`x=[1,2,4,5,8,9]`

What I wanted to implement is to get a list which contains combination of 4 digits out of the list. For example: Output should be

``````[1,2,4,5]
[2,3,4,8]
.....
[1,3,5,8]
....
``````

Hence, I believe it will be `4^6` solutions. I have tried itertools combination with no success

Itertools is actually the answer, because what you want are permutations of length N.

``````import itertools as it
x=[1,2,4,5,8,9]
print(list(it.permutations(x, 4)))
``````

If order does not matter you should use `itertools.combinations`:

``````from itertools import combinations
x=[1,2,4,5,8,9]
for c in combinations(x, 4):
print(c)
``````

This outputs:

``````(1, 2, 4, 5)
(1, 2, 4, 8)
(1, 2, 4, 9)
(1, 2, 5, 8)
(1, 2, 5, 9)
(1, 2, 8, 9)
(1, 4, 5, 8)
(1, 4, 5, 9)
(1, 4, 8, 9)
(1, 5, 8, 9)
(2, 4, 5, 8)
(2, 4, 5, 9)
(2, 4, 8, 9)
(2, 5, 8, 9)
(4, 5, 8, 9)
``````

You can try this:

``````from itertools import combinations
x=[1,2,4,5,8,9]
comb = list(map(list, itertools.combinations(x, 4)))
print(comb)
[[1, 2, 4, 5], [1, 2, 4, 8], [1, 2, 4, 9], [1, 2, 5, 8], [1, 2, 5, 9], [1, 2, 8, 9], [1, 4, 5, 8], [1, 4, 5, 9], [1, 4, 8, 9], [1, 5, 8, 9], [2, 4, 5, 8], [2, 4, 5, 9], [2, 4, 8, 9], [2, 5, 8, 9], [4, 5, 8, 9]]
``````
POPULAR ONLINE

### How can I count the number of elements in the values of a dictionary? [on hold]

I have a a few dictionaries like this

36

### create a Dynamic mapping for parsing multiple input files to an obj in kotlin

Let's say I have a json data that can have different Key names for the same data field

32

### Spark (AWS EMR): Update to emr-5.20 (with Spark 2.4) : Paralellism is not inherited

We have updated aws emr to version 520 from 5

40

### How can I split string by a special character and ignore everything inside parentheses?

I want to split the string by "/" and ignore "/" inside the outer parentheses

46