Another use cases for lambdas functions please? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 2

Another use cases for lambdas functions please?

https://code.sololearn.com/cLHh71qU3VYq/?ref=app

29th Aug 2023, 11:40 AM
Ernesto Trujillo
Ernesto Trujillo - avatar
7 Respuestas
+ 2
you can use it as a function for map in generator expressions print(*(map(lambda x: 0 if x%2==0 else x, (1,2,3,4,5,6))))
29th Aug 2023, 12:39 PM
Bob_Li
Bob_Li - avatar
+ 4
Another test, but a bit more complex task. map is mostly unable to beat generartor exression (if you run the tests repeatedly, it sometimes does). Again, the difference is small. My view is it is unnecessary to worry about which is faster. The effect is minimal. if you're after blazingly fast, python is the wrong choice. it's getting OT. The original question was about lambda functions, so I thought I'd add a lambda in the map. https://code.sololearn.com/cYxtYzShEHTu/?ref=app
30th Aug 2023, 5:58 AM
Bob_Li
Bob_Li - avatar
+ 3
Angela right. list comprehension is faster. It was just something I thought of for lambda function use case. but if you can write lambda, you will find writing comprehensions and generators easier.
29th Aug 2023, 3:36 PM
Bob_Li
Bob_Li - avatar
+ 3
Mirielle interesting. So generators are faster than map only for small values. I would have thought that the conversion to list would be a bottleneck. The result is reversed if you increase the range to higher values, though. But the difference seems slight. All said, if you want speed and dealing with big data, pure Python probably is the wrong language for it. I've been learning Rust and writing modules for Python gives very impressive results. But learning Rust is not easy at all... I modified your code so that the comparison is between list from map and list comprehension. https://code.sololearn.com/c8GL79V8xL3Q/?ref=app
30th Aug 2023, 2:51 AM
Bob_Li
Bob_Li - avatar
+ 3
Mirielle true. But I doubt micro optimizations like these would actually make an entire program blazingly fast. In most use cases, you could use one or the other and get the job done without much noticeable difference.
30th Aug 2023, 11:52 AM
Bob_Li
Bob_Li - avatar
+ 1
i have attached a example: Do not use map() and filter(). List comprehensions and generators were created to replace map() and filter() in nearly every case. https://code.sololearn.com/cCP3l7VE1t42/?ref=app
29th Aug 2023, 2:52 PM
Angela
Angela - avatar
+ 1
Thanks for the help Mirielle, Bob_Li and Angela
30th Aug 2023, 1:20 PM
Ernesto Trujillo
Ernesto Trujillo - avatar