2

i'm new in python, i'm learning about lambda and map, but when i was trying some things, i found that one loop was not executing, and i want to know why.

I know it's kind useless to do that, but when i iterate the same list two times, the second time is not executed.

salarios = map(lambda emp: emp.salario, empleados)
print("------SALARIO-------")
for salario in salarios:
    print(salario)
print("-----SALARIO2--------")
for salario in salarios:
    print(salario)

I get

------SALARIO-------
6700
7500
2100
2150
1800
-----SALARIO2--------

i expect get

------SALARIO-------
6700
7500
2100
2150
1800
-----SALARIO2--------
6700
7500
2100
2150
1800

why is it happend? it's some lenguaje optimization?

Raikish
  • 634
  • 2
  • 6
  • 20

1 Answers1

8

yes, map is a generator (since Python 3). Once consumed in the first loop, it's "empty" the second time.

You'd be better off without map + lambda combination (that's a general rule). In your case, change:

salarios = map(lambda emp: emp.salario, empleados)

by

salarios = [emp.salario for emp in empleados]

now you have a list comprehension, which you can iterate as many times as you want.

(your current expression is equivalent to generator comprehension salarios = (emp.salario for emp in empleados) which is easier to read when you only want to iterate only once on it)

Note: in Python 2 map returns a list, so people abused of map and lambda expressions, sometimes even without iterating, just to call a function on elements of a list.

With Python 2, your code would have worked, but would have had a vicious portability bug when switching to Python 3 (The list(map(lambda emp: emp.salario, empleados)) expression that 2to3 tool proposes fixes that, but is slower & even harder to read than a comprehension)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219