Python Forum
Adding values with reduce() function from the list of tuples
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding values with reduce() function from the list of tuples
#1
Hi,
I've been trying to use reduce() function to add values in the list of tuples. I'm only interested to add and display the numbers, but I don't know how to access and operate only on the second column(numbers)

I've tried to do it using regular function and then the reduce()

What am I doing wrong?

import functools

list = [("Rachel",19),
           ("Monica",18),
           ("Phoebe",17),
           ("Joey",16),
           ("Ross",20),
           ("Chandler",21)]

def func(self):
    x = list[0][1]
    y = list[1][1]
    return x+y

func_x = func(self="")
print(func_x)

ages_added = functools.reduce(lambda x,y:x[1][1]+y[1][1],list)
print(ages_added)
Larz60+ write Jan-05-2023, 12:28 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button
Fixed for you this time. Please use BBCode tags on future posts.
Reply
#2
Firstly, the name of the list should not be named list because list is a built-in function.
To get the second values from the tuple, you must iterate over the data.
data = [
    ("Rachel", 19),
    ("Monica", 18),
    ("Phoebe", 17),
    ("Joey", 16),
    ("Ross", 20),
    ("Chandler", 21),
]


for elements in data:
    print(elements)
    # ("Rachel",19) ...

for elements in data:
    print(elements[1])  # print second element

for name, age in data:
    print(age)
    # but name is not used, so you can assgn it the the thow away variable _


for _, age in data:
    print(age)
Or if you want to create a new list only with the second values of the tuples:
from operator import itemgetter

def get(data, index):
    getter = itemgetter(index)
    return [getter(values) for values in data]

# without itemgetter
def get(data, index):
    return [values[index] for values in data]


data = [
    ("Rachel", 19),
    ("Monica", 18),
    ("Phoebe", 17),
    ("Joey", 16),
    ("Ross", 20),
    ("Chandler", 21),
]

ages = get(data, 1)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thank You

That totally works! Big Grin Although what I'm looking for is to use the reduce function to add up all the numbers.

I figured out the way to iterate over the second column...

second_column = (lambda x:x[1])
...but can't find the way to use it in the functools.reduce()

Anyway, maybe it can't be done Think
Reply
#4
It's certainly possible, but I wouldn't do it due to the asymmetry.
>>> friends
[('Rachel', 19), ('Phoebe', 17), ('Joey', 16), ('Ross', 20), ('Chandler', 21)]
>>> reduce(lambda x,y:x+ y[1], friends, 0)
93
This makes use of the fact that you only need the second element from the new items as they are brought in, but you add it to the entire accumulator. And by initializing the accumulator to 0, it's always present.

Alternatively, instead of returning an int, you can return a tuple with the answer in the second column. Then the addition is natural, but you have to massage the answer when complete.

>>> reduce(lambda x,y:(None, x[1] + y[1]), friends)
(None, 93)
Reply
#5
Personally, I'd break the problem down into steps: turn the list of people into just a list of ages (which is a map or list comprehension) and then add those up (the reduce).

The third party Tools library has functions that can make these sorts of pipelines read quite nicely: https://toolz.readthedocs.io/en/latest/a...read_first.
Reply
#6
(Jan-05-2023, 06:03 PM)kinimod Wrote: Although what I'm looking for is to use the reduce function to add up all the numbers.

Alternative to bowlofred solution is to stream only age and use lambda to add up:

from functools import reduce

data = [("Rachel",19),
        ("Monica",18),
        ("Phoebe",17),
        ("Joey",16),
        ("Ross",20),
        ("Chandler",21)]

total = reduce(lambda x, y: x+y, (age for _, age in data))

# total -> 111
Of course, for adding there is built-in function sum:

sum(age for _, age in data)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
Since reading this thread I've been looking for an example where reduce was a better choice than any other python construct. I did not fine any. Every example I found for reduce() could be written shorter and clearer using a comprehension.
from functools import reduce
from time import time

values = [('A', b) for b in range(10000000)]

start = time()
print(reduce(lambda a, b: a + b[1], values, 0))
print(time() - start)

start = time()
print(sum((value[1] for value in values)))
print(time() - start)
Output:
49999995000000 0.7833819389343262 49999995000000 0.7230224609375
The comprehension is even a tiny bit faster.
Reply
#8
(Jan-23-2023, 04:23 AM)deanhystad Wrote: Since reading this thread I've been looking for an example where reduce was a better choice than any other python construct. I did not fine any. Every example I found for reduce() could be written shorter and clearer using a comprehension.

I believa that before comprehension came along something like this was quite common:

from functools import reduce
from operator import add

data = range(10000000)

print(reduce(add, data))
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
const listOfTuples = [
[1, 2],
[3, 4],
[5, 6],
[7, 8],
];

const sum = listOfTuples.reduce((acc, cur) => acc + cur[0] + cur[1], 0);

console.log(sum); // Output: 36
Reply
#10
Not great examples. I see why it was demoted from builtins and exiled to functools.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Copying the order of another list with identical values gohanhango 7 1,134 Nov-29-2023, 09:17 PM
Last Post: Pedroski55
  Search Excel File with a list of values huzzug 4 1,216 Nov-03-2023, 05:35 PM
Last Post: huzzug
  Comparing List values to get indexes Edward_ 7 1,138 Jun-09-2023, 04:57 PM
Last Post: deanhystad
  reduce nested for-loops Phaze90 11 1,867 Mar-16-2023, 06:28 PM
Last Post: ndc85430
  user input values into list of lists tauros73 3 1,064 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  function accepts infinite parameters and returns a graph with those values edencthompson 0 855 Jun-10-2022, 03:42 PM
Last Post: edencthompson
  AttributeError: 'list' object has no attribute 'values' ilknurg 4 14,943 Jan-19-2022, 08:33 AM
Last Post: menator01
  Need to parse a list of boolean columns inside a list and return true values Python84 4 2,102 Jan-09-2022, 02:39 AM
Last Post: Python84
  List of dataframe values beginning with x,y or z glidecode 3 1,929 Nov-08-2021, 10:16 PM
Last Post: glidecode
  How to pass list of values to a API request URL chetansaip99 0 3,522 Sep-28-2021, 07:37 AM
Last Post: chetansaip99

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020