Home > OS >  Flatten list of lists and strings into one single list of strings
Flatten list of lists and strings into one single list of strings

Time:03-11

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)

I was wondering if there is a more Pythonic way to achieve the same result?

CodePudding user response:

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)

CodePudding user response:

A more concise approach is:

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