Search code examples
pythonpython-itertools

Merging the results of itertools.product?


I am trying to create a list of numbers from 0-9999 using itertools.product. I am able to create a list from 0000-9999 by doing the following:

numbers = ['0','1','2','3','4','5','6','7','8','9']
itertools.product(numbers,numbers,numbers,numbers)

And while I want entries like 0001, I would also like to get 001, 01, and 1.

What would be the most effective way to include these? Should I make calls to itertools.product(numbers,numbers,numbers) and itertools.product(numbers,numbers) and then somehow combine these with the original or is there a cleaner way?

If I should make two other calls and combine, can someone point me towards how this would be done? I attempted to use .append(), but it throws this error:

'itertools.product' object has no attribute 'append'

Thanks for any help.


Solution

  • You could use a nested listcomp or genexp (reduced in size here for display purposes):

    >>> numbers = ['0','1','2']
    >>> [''.join(p) for n in range(1,4) for p in product(numbers, repeat=n)]
    ['0', '1', '2', '00', '01', '02', '10', '11', '12', '20', '21', '22', '000', '001', '002', '010', '011', '012', '020', '021', '022', '100', '101', '102', '110', '111', '112', '120', '121', '122', '200', '201', '202', '210', '211', '212', '220', '221', '222']