'Flattening a list of strings and lists to work on each item [closed]

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.



Solution 1:[1]

A more concise approach is:

for entry in initial_list:
    for term in ([entry] if isinstance(entry, str) else entry):
        do_something(term)

Solution 2:[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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kodiologist
Solution 2 not_speshal