Search code examples
pythontext

How to insert a newline in printing list in itertools


I am permuting a few list. How to print the result in a newline?

Code:

import itertools

s=[ [ '1', '2','3'], ['a','b'],
['4','5','6','7'],
    ['f','g','e','y']]

print (list(itertools.product(*s,)))

Need Result:

#-- with a newline

1 a 4 f 
1 a 4 g 
1 a 4 e 
1 a 4 y

Current Result:

#-- not very readable

[('1', 'a', '4', 'f'), ('1', 'a', '4', 'g'), ('1', 'a', '4', 'e'), ('1', 'a', '4', 'y')]

Solution

  • You can unpack the tuples to f-strings, and join them all using \n as a separator.

    import itertools
    
    s=[ ['1', '2','3'], 
        ['a','b'],
        ['4','5','6','7'],
        ['f','g','e','y'] ]
    
    print('\n'.join((f'{a} {b} {c} {d}' for a,b,c,d in itertools.product(*s,))))