1

Given:

[['A', 'B', 'C'], ['1', '2', '3'], ['Z', 'X']]

Is there a way to concatenate every element from the lists in the list for every index 1 to 1 not 1 to many without using a lot of for statements? And the output to be a list with every concatenation as its elements?

Expected output:

['A1Z','B2X', 'C3']
yatu
  • 86,083
  • 12
  • 84
  • 139
Henry-G
  • 131
  • 1
  • 8

2 Answers2

3

We want to zip the lists together. But if the lists are not of the same length, we need to pad them. itertools.zip_longest helps us with that:

from itertools import zip_longest

xss = [['A', 'B', 'C'], ['1', '2', '3'], ['Z', 'X']]
result = ["".join(xs) for xs in zip_longest(*xss, fillvalue="")]

Which gives:

>>> result
['A1Z', 'B2X', 'C3']
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
0

A beginner-friendly solution

s = [['A', 'B', 'C'], ['1', '2', '3'],['Z', 'X']]
f = []

n = 0
while n != len(s):
    t = ''
    for i in s:
        try: t = t + i[n]
        except IndexError: pass
    f.append(t)

    n = n + 1
print(f)
Rajas Rasam
  • 175
  • 2
  • 3
  • 9