Cast an Array of Items using Lambdas and Map In Python
Let’s cast an array of items using lambdas and map in Python. It’ll look cleaner than its forloop counterpart.
My Setup
Python 3.x
macOS
The Problem
You have an array full of stuff that’s the wrong data type! Maybe you have numbers that you need as strings or vice versa.
before_cast = [1,2,3,4]
The Solution Using Lambdas and Map
before_cast = [1,2,3,4]
after_cast = list(map(lambda chunk: str(chunk), before_cast))
Explanation
So you start off with your typical array of integers with the goal of getting it to an array of strings. The str(chunk) is going to get applied to each element of the array using the map function. Alone, lambdas don’t loop. The map function is doing the loop. So map takes each element of an array and returns an array. In this case it takes each element of the before_cast array, casts the element to a string using str(chunk), and then returns the string element back into an array which we then cast back into a list. It’s a little around the way, but a great way to one line a long loop! Happy coding!