-5

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"

CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108
Tom Krakov
  • 71
  • 4

4 Answers4

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
jdehesa
  • 58,456
  • 7
  • 77
  • 121
0

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

Rajan Chauhan
  • 1,378
  • 1
  • 13
  • 32
0
In [14]: ' '.join([' '.join(x + i for i in listb) for x in listA])
Out[14]: 'a1 a2 a3 b1 b2 b3'
Cory Madden
  • 5,026
  • 24
  • 37
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.

Rahul P
  • 2,493
  • 2
  • 17
  • 31