Home > Enterprise >  How do I create a list of every combination of 3 digit numbers in Python?
How do I create a list of every combination of 3 digit numbers in Python?

Time:06-21

I'm trying to write a python script that would output:

000

001

002

... etc

but I'm running into difficulties. What I have so far is:

from itertools import product


list = [x for x in range(0, 10) if True]
for x in product(list, repeat=3):
    list3 = list(x)


def convert(l):
    c = [str(i) for i in l]
    list2 = int("".join(c))
    return(list2)

print(convert(list3))

but this only outputs:

999

I'm not sure how to get the full list. If I comment out the convert function it provides multiple lists of the numbers, like so:

[0, 0, 0]

[0, 0, 1]

...

Any help would be appreciated, I'm pretty sure I'm missing something simple.

CodePudding user response:

You're overthinking it.

for n in range(0, 1000):
    print(f'{n:03}')

CodePudding user response:

import itertools
import string

for t in itertools.product(string.digits, repeat=3):
    print("".join(t))

CodePudding user response:

if you want to use itertools you can also do:

from itertools import combinations

lst = [x for x in range(0, 10) if True]
combos = list(combinations(lst, 3))

documentation on itertools.combinations is here: https://docs.python.org/3/library/itertools.html#itertools.combinations

  • Related