[Tutor] Was: flatten a python list

dn PyTutor at DancesWithMice.info
Tue Jun 1 21:35:36 EDT 2021


On 02/06/2021 01.23, Mats Wichmann wrote:
> On 5/30/21 9:58 PM, Manprit Singh wrote:
>> consider a problem to get a flat list for below given list :
...

> 
> How about this for grins, should handle the "arbitrary layout" question
> Alan raised.
> 
> def flatten(lst):
>     for item in lst:
>         if not isinstance(item, list):
>             yield item
>         else:
>             yield from flatten(item)
> 
> lst = [[2, 6], [5, 8], [6, 0]]
> ans = list(flatten(lst))
> print(ans)
> [2, 6, 5, 8, 6, 0]
> # you can leave out the list() if an iterator is ok for your use
> 
> This has some flaws - but the other approaches do, too.  e.g. what if
> some item is a tuple, or a string is passed...  In a lot of cases this
> probably isn't what you want:
> 
> print(list(flatten("a string")))
> ['a', ' ', 's', 't', 'r', 'i', 'n', 'g']
> 
> in other words, as a general purpose approach you'd want to do some data
> validation.


What happens if we broaden the original spec from "list" to strings (as
above), and then continue into tuples, dictionary (keys or values),
classes, etc?

Is there a generic Python function which advises if a value is atomic or
some form of container?
(yes, could check for __contains__ method, but...)

Thus (from above code):
if value is atomic then copy to output else dive into container...
-- 
Regards,
=dn


More information about the Tutor mailing list