Andrew Andrew - 2 months ago 9
C# Question

What is the Python equivalent to C# LINQ Sum()

In C# I can get the sum of some values like so:

new List<Tuple<string, int>>().Sum(x => x.Item2);


How can I achieve the same result in Python? Assuming I have a list of tuples

Answer

The equivalent is a comprehension inside a sum().

sum(x[1] for x in tuples)

For example, we can define some sample random data.

from random import randint

r = lambda: randint(0, 100)

data = [(r(), r(), r()) for x in range(100)]

sum(x[1] for x in data)