0

I want to use a triple list comprehension in python to to make a flat list.

mynested = [[['1229'], [['2020-11'], ['2020-1'], ['2020']]], [['1230'], [['2020-12'],['2020-2'], ['2020']]]]

I would like it to work like this.

short=[]
for a in mynested:
    for b in a:
        for c in b:
            short.append(''.join(c))
for shrt in short:
    print(shrt)

Outcome:

1229
2020-11
2020-1
2020
1230
2020-12
2020-2
2020

But how do I get this outcome with a list comprehension?

tinus
  • 149
  • 1
  • 7
  • 3
    You cannot get "prints" from a list comprehension. Do you mean something else? – ShlomiF Jul 11 '21 at 18:33
  • 1
    Nested list comprehensions are not all that mysterious. The loop structures appear in the same order whether inline or not `[''.join(c) for a in mynested for b in a for c in b]` if you know the nested loop structure you know the list comprehension structure. – Henry Ecker Jul 11 '21 at 18:35
  • It's not as easy as you imply. Some of your strings are nested 3 levels deep ('1220'), some are nested 4 levels deep ('2020-11'). – Tim Roberts Jul 11 '21 at 18:37
  • 2
    List comprehensions are for *building* lists, not printing their contents. – martineau Jul 11 '21 at 18:38
  • You can definitely use `print` in a list comprehension **but you shouldn't** – juanpa.arrivillaga Jul 11 '21 at 18:40

2 Answers2

1

I don't know what you mean by getting an "output" of "prints", but doing what you want with a triple-nested list is very similar to a double-nested list.
So how about -

output = [''.join(x) for z in mynested for y in z for x in y]

You can now do -

for x in output:
    print(x)

# 1229
# 2020-11
# 2020-1
# 2020
# 1230
# 2020-12
# 2020-2
# 2020
ShlomiF
  • 2,686
  • 1
  • 14
  • 19
1

Update: You could try this, it gives the desired output:

print(*[''.join(c) for a in mynested for b in a for c in b], sep='\n')

You cannot make a print function in a list comprehension because that will return None values. For instance this example:

numbers = [1,2,3]
[print(x) for x in numbers]

the output will be the numbers in the list and also a list of three None values.