user4333465
user4333465

Reputation:

When to use for loop vs one-liner

Is there any difference in performance between a one-liner like the one in the example below, or the for loop? Here's a snippet of code that I was using to do stuff:

# convert to integer, subtract 1, and change to 0 if number is < 0
tile_ids =  map(lambda x: max(int(x)-1, 0), child[0].text.split(','))

Is it better to do that, or write out this:

for tile_id in child[0].text.split(','):
    tile_id = int(tile_id) - 1
    if tile_id < 0:
        tile_id = 0

Also, is there a reason to use one over the other?

Upvotes: 2

Views: 1166

Answers (1)

Marco Favorito
Marco Favorito

Reputation: 410

For this specific case, you don't gain so much in terms of performance using a map instead of a for-loop. Probably, using the map is a bit worse than the latter approach, since you are implicitly using "extra-stuff" that, in this case, is not very useful.

The "map-approach" can be very useful when you have the capabilities to parallelize tasks. In that case you can surely achieve better performances than a plain for-loop.

I prefer the second version, thanks to readability. Another way is to use a list-comprehension:

title_ids = [max(int(x)-1,0) for x in child[0].text.split(',')]

Upvotes: 1

Related Questions