[Tutor] flatten a python list
Mats Wichmann
mats at wichmann.us
Tue Jun 1 09:23:49 EDT 2021
On 5/30/21 9:58 PM, Manprit Singh wrote:
> Dear sir,
>
> consider a problem to get a flat list for below given list :
> lst = [[2, 6], [5, 8], [6, 0]]
> the flatten list will be :
> ans = [2, 6, 5, 8, 6, 0]
>
> I have seen in several texts around the internet and even in the textbooks,
> the approach followed is to use nested for loop.
> ans = []
> for ele in lst:
> for num in ele:
> ans.append(num)
>
> instead of using this for loop if i write :
> ans = []
> for ele in lst:
> ans.extend(ele)
>
> Although the answer is correct, I need your comments on this approach.
>
> Just for the sake of healthy discussion, i am putting this question
> Although i can do it in a very efficient manner with list comprehension as
> given below:
> ans = [num for ele in lst for num in ele]
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.
More information about the Tutor
mailing list