2021-03-15 22:04:11

When i look at it i don't know if ever i will need it. probabely  the function is useful but, i wonder if ever You've used it.

2021-03-15 22:10:34

You'll probably never use it.  It doesn't come up very often and, in Python, it doesn't look so nice as it does in languages with better iterator support.  Also, in Python 3 you have to use functools.reduce instead.

Just use for loops.  Unless it's something incredibly, incredibly simple for loops are easier to figure out.

My Blog
Twitter: @ajhicks1992

2021-03-15 22:46:42

@Kamlorn

Yea i use python3, it looks highly messy with lambdas imho. What is Your openion about that?

2021-03-16 00:25:50

I don't know what you're asking.  My opinion about lambdas in general?

My Blog
Twitter: @ajhicks1992

2021-03-16 19:15:14 (edited by Turkce_Rap 2021-03-16 19:16:14)

@Kamlorn
No i was meaning "Reduce func" looks too messy when it's been used within Lambdas altogether.

2021-03-16 19:54:27

yes.  That's because Python doesn't let you write it left to right.  In Rust, if I had a list:

let product_of_evens = mything.iter()
    .filter(|x| x%2 == 0)
    .fold(1, |x, y| x * y)

Finds all the even numbers in the list, then multiplies them together.

But you're never going to make it look this nice in Python, no.

My Blog
Twitter: @ajhicks1992

2021-03-16 20:51:55

reduce is basically the functional version of a for loop. as you've noticed and Camlorn pointed out, it really is not very nice to use in python, so better to stick to for loops and list comprehensions. generally, functional style programming is impractical in python, because its syntax for lambdas, makes them impractical except for one liner functions.

in other languages, with better lambda syntax, reduce is very useful and I use it all the time.

such languages include all functional languages under the sun (Scala, Haskell, Rust, etc.), but lambda syntax is also quite nice for JavaScript and Java, where I use reduce more often than a for loop.