Python – Concatenating and printing the elements of a 3D list

I am trying to combine the elements of a 3D string list into a single string.

eleli = [[["ele1"]], [["ele2"]], [["ele3"]], [["ele4"]], [["ele5"]]]

elecom = [i for i in eleli for i in i for i in i]

lali = ""
for a in elecom:
    lali += a + "\n"

print(lali)

>>>ele1
ele2
ele3
ele4
ele5

The above operation will give you the desired result. But the code is too stupid. Can you make it simpler?

>Solution :

We can actually use a single list comprehension here along with join():

eleli = [[["ele1"]], [["ele2"]], [["ele3"]], [["ele4"]], [["ele5"]]]
output = "".join([x[0][0] for x in eleli])
print(output)  # ele1ele2ele3ele4ele5

To address the input suggested by @anto, we can try:

eleli = [[["ele1"]], [["ele2","other_ele2"]], [["ele3"]], [["ele4"]], [["ele5"]]]
output = "".join(["".join(x[0]) for x in eleli])
print(output)  # ele1ele2other_ele2ele3ele4ele5

Leave a Reply