Operation on list in list of list using list comprehension

Question:

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)]

    I am trying to get it using list comprehension.

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

Asked By: Ash3060

||

Answers:

this should do the trick:

l=[1,3,4,5,6,7],[1,1],[1,9,9]
nl= [("sum",len(lst)) for lst in l]
print(nl)

output:

[('sum', 6), ('sum', 2), ('sum', 3)]

if you have any question about the code feel free to ask me in the comments 🙂

Answered By: Ohad Sharet

I guess what you want is

print(list(map(lambda x: ("sum",sum(1 for i in x)),l))) 

The the mapping function has an agrument x, when you iterate over l to get the sum you are accessing the global l variable.

Answered By: Bob

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]
Answered By: timgeb

That’s what you want

l=[1,3,4,5,6,7],[1,1],[1,9,9]
print([('sum', len(l_)) for l_ in l])

Output:

[('sum', 6), ('sum', 2), ('sum', 3)]

But i think that is not sum, it’s len, so:

l=[1,3,4,5,6,7],[1,1],[1,9,9]
print([('len', len(l_)) for l_ in l])

Output:

[('len', 6), ('len', 2), ('len', 3)]
Answered By: 555Russich
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.