Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python map object methods

Tags:

python

I am looping through an array of objects, calling a method on each like so:

for cell in cells:
    cell.update_type(next_cells[cell.index])

Is there a way to do the equivalent with map()?

like image 622
Ferguzz Avatar asked Jan 19 '23 09:01

Ferguzz


1 Answers

It appears update_type returns None, so you could use:

any(cell.update_type(next_cells[cell.index]) for cell in cells)

but unless there is a problem with a normal loop, just stick with that. It's the most readable and you shouldn't optimize prematurely.

You shouldn't use map here because there is no way to avoid using it on a Python function / lambda expression, so you won't get a speed advantage over a normal loop.

You shouldn't use a list comprehension because you're needlessly accumulating a list of the return values of update_type even though you're ignoring them -- use any instead.

like image 165
agf Avatar answered Feb 01 '23 00:02

agf