Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Operation on list in list of list using list comprehension

I am trying to print a list of tuples containing the size of each list from list of list

ex:

l=[1,3,4,5,6,7],[1,1],[1,9,9]

print(list(map(lambda x: ("sum",sum(1 for i in l)),l))) 
  • The output is coming as [(‘sum’, 3), (‘sum’, 3), (‘sum’, 3)]

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    I am trying to get it using list comprehension.

  • The expected output I want should be
    [(‘sum’,6),(‘sum’,2),(‘sum’,3)]

>Solution :

You have a bug, it should be

sum(1 for i in x) # x, not l

Also, len(x) would give you the same number.

The list-comprehension solution is

[('sum', len(x)) for x in l]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading