[Tutor] flatten a python list

Manprit Singh manpritsinghece at gmail.com
Sun May 30 23:58:16 EDT 2021


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]

Regards
Manprit Singh


More information about the Tutor mailing list