Cast an array of items using lambdas in Python.

Cast an array of items using lambdas in Python.

Let’s cast an array of items using lambdas in Python. It’ll look cleaner than its forloop counterpart. They’re a great way to clean up super verbose code and helpful when doing array manipulation.

Before we begin, if you don’t know what a Python lambda is please check out this article we recently wrote.

My most recent usecase was casting an array of items from one type to another. We’ll show you how to get this done in a single line!

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. You can also use this methodology for string manipulation like concatenating stuff to each element of an array.

Alright let’s call it what it is, you can do most of the stuff you can do with a forloop, but in a prettier fashion. Alright let’s show you how to cast an array of items using lambdas in Python.

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!

Using the same methodology we can create a list of objects from an array of data to leverage whatever methods those objects contain.

Happy coding!

Check out this article for some Python class fun.