Stop Writing C in Python: map to the Rescue

Al Williams
Geek Culture
Published in
3 min readAug 27, 2021

--

A better way to loop

Photo by Thomas Kinto on Unsplash

As a very old C programmer, I find, sometimes, that I am writing C in whatever language I’m using. If you have this problem, you should look at other ways to more efficiently code in other languages like Python. For example, one of the calls mentioned by Emmett Boudreau in a recent post is map — a function that can efficiently replace loops in Python.

If you are a C programmer, you think of looping through an array or a list using a for loop. You can certainly do that in Python, too:

def doubling(x):
return (2*x)
testlist = [ 1, 2, 3, 4, 100 ]outp=list()
for x in testlist:
outp.append(doubling(x))

print(outp)

That isn’t hard and if I didn’t want to create a new list, I could have printed the items one at a time. But in a real program I probably am more interested in building the list for use somewhere else and the print is just an artifact of this being a simple test.

The map function lets you apply a function to each element of a list and it returns a map which you can cast to a list (among other things). Here’s an example:

def doubling(x):
return (2*x)
testlist = [ 1, 2, 3, 4, 100 ]print(list(map(doubl…

--

--

Al Williams
Geek Culture

Engineer. Author. Team Leader. Lots of other things. I blog about hardware hacking for Hackaday (www.hackaday.com), but talk about other topics here.