2

The following python code gives me the different combinations from the given values.

import itertools

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]
for t in itertools.product(*iterables):
    print t

Output:-

(1, 88, 'a')
(1, 88, 'b')
(1, 99, 'a')
(1, 99, 'b')
(2, 88, 'a')

and so on.

Can some one please tell me how to modify this code so the output looks like a list;

188a
188b
199a
199b
288a
1
  • 2
    Your output doesn't look like a list. Presumably you meant that the output should not look like tuples but simply joined? Commented Jun 4, 2017 at 15:09

2 Answers 2

5

You'll have to convert the numbers to strings, then join the results:

print ''.join(map(str, t))

You could avoid having to convert if you made your inputs strings to begin with:

iterables = [['1', '2', '3', '4'], ['88', '99'], ['a', 'b']]
for t in itertools.product(*iterables):
    print ''.join(t)

If all you want is to print the values together (and not do anything with them otherwise) then use print() as a function (by using the from __future__ import print_function Python 2 feature switch or by using Python 3):

from __future__ import print_function

iterables = [[1, 2, 3, 4], [88, 99], ['a', 'b']]
for t in itertools.product(*iterables):
    print(*t)
Sign up to request clarification or add additional context in comments.

Comments

5

You can try this:

iterables = [ [1,2,3,4], [88,99], ['a','b'] ]

new_list = [''.join(map(str, i)) for i in itertools.product(*iterables)]

2 Comments

Why the list in the map? Just do map(str, i)
@rassar: in Python 2, yes, not so in Python 3 (as str.join() works faster with list inputs).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.