0

I am currently working with different input types -

My input could either look like this:


 [term1, term2, term3,...]  

or

[[term1, term2], term3] 

or

[[term1, term2], [term3, term4]]

I would like to find a way to flatten it to a format over which I could loop in order to use the terms.

My code at the moment looks like this:


for entry in initial_list:
    if type(entry) is str:
       do_something(entry)
    elif type(entry) is list:
       for term in entry:
          do_something(term)

The goal would be to perform the flattening in a more Pythonic way, using list comprehension or mapping, instead of explicit for loops.

jinx
  • 173
  • 2
  • 12
  • Does this answer your question? [How to make a flat list out of a list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) –  Mar 10 '22 at 17:53
  • @SembeiNorimaki - That only works if every element of the list is another list. OP has mentioned that some of their items are strings. – not_speshal Mar 10 '22 at 18:01
  • @Sembei Norimaki, Not quite. The answers there assume a uniform list of lists. – ikegami Mar 10 '22 at 18:01
  • @ikegami in the linked question they propose using `merged = list(itertools.chain(*myList))` which works for me in the three cases the OP requested –  Mar 10 '22 at 18:05
  • @SembeiNorimaki in the case of 3 strings in the list, the method you mention splits them on a character by character basis – jinx Mar 10 '22 at 23:06
  • Does this answer your question? [Flatten an irregular list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – MisterMiyagi May 16 '22 at 09:50
  • 2
    This post is being discussed [on meta](https://meta.stackoverflow.com/questions/418099/opinionated-question-for-performance-and-readability-improvements). – MisterMiyagi May 16 '22 at 09:50

2 Answers2

2

You're very close. It might however be better to use isinstance. Try:

result = list()
for entry in initial_list:
    if isinstance(entry, str):
        result.append(entry)
    elif isinstance(entry, list):
        for term in entry:
            result.append(term)
not_speshal
  • 22,093
  • 2
  • 15
  • 30
1

A more concise approach is:

for entry in initial_list:
    for term in ([entry] if isinstance(entry, str) else entry):
        do_something(term)
Kodiologist
  • 2,984
  • 18
  • 33