Home > Software engineering >  How do I sum the first two values in each tuple in a list of tuples in Python?
How do I sum the first two values in each tuple in a list of tuples in Python?

Time:10-27

I searched through stackoverflow but couldn't find an answer or adapt similar codes, unfortunately. The problem is that I have a list of tuples:

tupl = [(5,3,33), (2,5,2), (4,1,7)]

and I should use list comprehension to have this output:

[8,7,5]

The code that I wrote is a bit dump and is:

sum_tupl = []
tupl = [(5,3,33), (2,5,2), (4,1,7)]
sum_tupl = [tupl[0][0] tupl[0][1] for tuple in tupl]
sum_tupl

but instead of doing what I want it to do, it returns

[8,8,8]

which is the sum of the first couple executed three times. I tried using a variant:

tupl = [(5,3,33), (2,5,2), (4,1,7)]
sum_tupl = [sum(tupl[0],tupl[1]) for tuple in tupl]
sum_tupl

(which is missing something) but to no avail.

CodePudding user response:

Note: When you're beginning python, it's much easier to use loops instead of list comprehensions because then you can debug your code more easily, either by using print() statements or by stepping through it using a debugger.


Now, on to the answer:

When you do for x in y, with a list y, the individual items go in x. So for your code for tuple in tupl, you shouldn't use tupl because that is the entire list. You need to use the individual item in the list, i.e. tuple.

Note that it's not a good idea to name a variable tuple because that's already a builtin type in python.

You need:

tupl = [(5,3,33), (2,5,2), (4,1,7)]
sum_tupl = [t[0] t[1] for t in tupl]

Which gives the list

sum_tupl: [8, 7, 5]

If you have more elements you want to sum, it makes more sense to use the sum() function and a slice of t instead of writing out everything. For example, if you wanted to sum the first 5 elements, you'd write

sum_tupl = [sum(t[0:5]) for t in tupl]

instead of

sum_tupl = [t[0] t[1] t[2] t[3] t[4] for t in tupl]

CodePudding user response:

Each loop iteration you're accessing the first element of your tupl list, instead of using the current element. This is what you want:

sum_tupl = [t[0]   t[1] for t in tupl]
  • Related