-4

I want to turn a take two lists and create one long string by looping over each string in each list and concatenating the two separating them by a space:

listA = ["a","b"]
listb = ["1","2","3"]

new_string = "a1 a2 a3 b1 b2 b3"

1
  • ' '.join(map(''.join, itertools.product(listA, listb))) Commented Aug 4, 2017 at 16:53

4 Answers 4

1

It is really simple
print( ' '.join([ str(i)+str(j) for i in listA for j in listB]))

Sign up to request clarification or add additional context in comments.

3 Comments

@whackamadoodle can you point out the mistake what it is specifically.
Sorry, I misinterpreted the question, mine does not work. I just deleted it
The method is great, but the result lacks the backspace. ' '.join([str(i)+str(j)+' ' for i in listA for j in listB]))
0

Try this:

from itertools import product

listA = ["a","b"]
listb = ["1","2","3"]
new_string = " ".join(a + b for a, b in product(listA, listb))
print(new_string)
>>> a1 a2 a3 b1 b2 b3

Comments

0
In [14]: ' '.join([' '.join(x + i for i in listb) for x in listA])
Out[14]: 'a1 a2 a3 b1 b2 b3'

Comments

0

Here is a pretty simple solution to the problem, it is usually taught in the beginning of learning for loops (at least it was for me):

listA = ["a","b"]
listb = ["1","2","3"]
new_string = ""

for i in listA:
    for j in listb:
        #adding a space at the end of the concatenation 
        new_string = new_string+i+j+" "


print(new_string)

Coded in python 3.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.