#๐Ÿ”’ Using lambda for list mapping

40 messages ยท Page 1 of 1 (latest)

spring pulsar
#
lst = [33, 3, 22, 2, 11, 1] 

lst1 = list(map(lambda x : x**2 , lst)) 
lst2 = [x**2 for x in lst]

Is there any reason to use lambda over the second option in this case?

covert elmBOT
#

@spring pulsar

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

vapid otter
#

map could be somewhat handy if you already have a named function. But if you need to introduce a lambda, just use a list comprehension or generator expression instead

spring pulsar
#

I see, so it would make sense for complex functions but not for simple lambda functions

#

Thank you

vapid otter
#

it would make sense if you already had a function that's already defined. Like ```py
def do_something(x):
...

things = list(map(do_something, inputs))

#

but even then it's totally fine to do [do_something(x) for x in inputs]

spring pulsar
#

oh yeah i didnt even think of that

#

I'm trying to find ways to use lambda, so far i know its nice to use for function creation

def salary(x):
    return lambda a : a * x

doubler = salary(2)
tripler = salary(3)

print(f' doubler : {doubler(22)}')
print(f' tripler : {tripler(22)}')

and for when you want to do operations (ex. sort) on an iterable with a filter

twin crest
vapid otter
zinc glacier
stark spade
# spring pulsar I'm trying to find ways to use lambda, so far i know its nice to use for functio...

I'm trying to find ways to use lambda
One example I just saw in my junk py file:

from typing import Callable

if __name__ == '__main__':
    binary_operations: dict[str, Callable] = {
        'add': lambda x, y: x + y,
        'multiply': lambda x, y: x * y,
        'divide': lambda x, y: x / y,
    }

    try:
        first_num, second_num = int(input("First number: ")), int(input("Second number: "))
        operation = input("Operation: ")
        print(binary_operations[operation](first_num, second_num))
    except ValueError:
        print("Invalid input")
#

Most of my lambda uses, that I could find in my junk py file at least, are passed to functools.reduce

spring pulsar
#

i'll have to check that out

#

thanks guys

worldly bear
#

also map is lazy if no-one mentioned that, that can be very important

worldly bear
spring pulsar
worldly bear
#

it means that:

def double(v):
   return v * 2


lst = [1, 2, 3]
lst2 = map(lambda x: double(x), lst)
# at this point, double has not been called.  map returns an iterable that will do the work on demand (when the iterator is consumed)

lst2 = list(lst2)
# now double has been called 3 times
#

that example up ther ealso demonstrates why lambdas are very, very rarely needed. you may as well write the above map call as:

lst2 = map(double, lst)

basically, anytime you use a lambda, you can probably just pass a defined function instead

#

(or a partial over a defined function)

vapid otter
#

and if you don't already have a function, you can get the same lazy behaviour with a generator expression ```py
lst2 = (x*2 for x in lst)

zinc glacier
# spring pulsar What does that mean

It means that it only creates its results as they are used.
This:

for s in [str(x) for x in (1,2,3)]:

first computes an entire list ["1", "2", "3"]. Then runs the for.
This:

for s in map(str, (1,2,3)):

computes a "map" iterator, which so far has done nothing, and the iterator only computes each item as the for-loop asks for it.

If you go:

for item in [really hughe list here]:
    if item == 3: break

the huge list is always computed entirely, even if. there's a 3 close to the start.

This:

for item in map(something......):
    if item == 3: break

only computes enough stuff to reach the 3.

spring pulsar
#

Map would also remove the item from memory if it doesn't == 3 correct?

#

Before computing the next item

#

Where as

for item in [really hughe list here]:
    if item == 3: break

keeps the whole list in memory until the for loop is over

zinc glacier
#

Well, it produces the item and then forgets it, yes. The for-loop hangs onto it for 1 iteration (as item), then forgets it.

zinc glacier
spring pulsar
#

good to know

zinc glacier
#

So map doesn't "remove it". Python keeps track of who has a reference to it. When nobody has a reference, Python removes it.

spring pulsar
#

yeah wrong to say that. map would forget about it and then python garbage collection would deal with it

safe basin
#

!d operator

covert elmBOT
#

Source code: Lib/operator.py

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. Many function names are those used for special methods, without the double underscores. For backward compatibility, many of these have a variant with the double underscores kept. The variants without the double underscores are preferred for clarity.

The functions fall into categories that perform object comparisons, logical operations, mathematical operations and sequence operations...

stark spade
covert elmBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.