2

I have three lists with the same number of elements of string type. And all I want to do is to join them together in one list.

list_1 = ['inline', '', '', '', '', '', '']
list_2 = ['static', 'static', 'static', '', 'static', 'static', 'static']
list_3 = ['boolean', 'uint8', 'uint8', 'void', 'boolean', 'void', 'void']

So my desired output would look like this:

print(result[0], result[1])
# Output
inline static boolean, static uint8

I tried using:

Joining two lists
list_type_12 = [i + j for i in list_type_1 for j in list_type_2]
print(list_type_12)
list_type_123 = [i + j for i in list_type_12 for j in list_type_3]
print(list_type_123)

But the output is a total mess, it creates every possible combination of those words. I know that it should be simple task to do, but I just can't do it properly. Please help me with solving this problem.

1 Answers1

3

If you are sure that all lists have the same number of elements, something simple as this will work :

output = []
for i in range(len(list_1)):
    output.append(f'{list_1[index]} {list_2[index]} {list_3[index]}')

If you do not know what the f before the string means, it will replace everything in curly brackets with the value of the expression.

You could also do something like this, which will scale better if you have more than 3 lists :

output = []
for elements in zip(list_1, list_2, list_3): # add more lists if necessary
    output.append(' '.join(elements))

This can of course be reduced to a one-liner (the first code can as well) :

output = [' '.join(elements) for elements in zip(list_1, list_2, list_3)]
charon25
  • 316
  • 2
  • 9