Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "map" function in Python? (How to rewrite a for loop?)

Tags:

python

map

I have an array of classes and I want to create objects of them. This works:

    classArray = [Auto, Wheel]
    objectArray = []
    for myClass in classArray:
        objectArray += [myClass()]

Can I use the map function to accomplish the same?

    objectArray = map( ??? , classArray)

My apologies if this is a dumb question. I am fairly new to Python.

Thanks!

like image 335
Lars Schneider Avatar asked Jan 17 '23 22:01

Lars Schneider


1 Answers

You could use a list comprehension instead. Many consider them to be preferred over the map function.

objectArrray = [ c() for c in classArray ]

If you insist on using map, you can do

map(lambda c: c(), classArray)

Here, I am creating an anonymous function with lambda that simply takes the item, and calls it. If you are unfamiliar with map, it takes a 1-parameter function as the first argument.

like image 133
Donald Miner Avatar answered Feb 23 '23 18:02

Donald Miner