#๐ Using lambda for list mapping
40 messages ยท Page 1 of 1 (latest)
@spring pulsar
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.
no, use a list comprehension
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
I see, so it would make sense for complex functions but not for simple lambda functions
Thank you
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]
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
one example is to bind a callback (with parameters) to an action when you build GUIs in some frameworks
it's very common to use a lambda as a key function to sorted, max or min
Doing operations for sort is also function generation, if you think about it that way ๐
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
also map is lazy if no-one mentioned that, that can be very important
because of the constraints of lambdas, you almost never actually need to use them
What does that mean
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)
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)
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.
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
Well, it produces the item and then forgets it, yes. The for-loop hangs onto it for 1 iteration (as item), then forgets it.
Yes, because the for-loop has a reference to the list. Which is huge.
Ah that's really cool
good to know
So map doesn't "remove it". Python keeps track of who has a reference to it. When nobody has a reference, Python removes it.
yeah wrong to say that. map would forget about it and then python garbage collection would deal with it
if you're already importing...
have a look into the operator module.
e.g.
from operator import add, mul, sub, ...
!d operator
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...
Ah cool. I now remember seeing that a long time ago, but I never really used it and eventually completely forgot about it.
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.