Home > Software engineering >  Don't understand why Map returns iterator makes code to fail
Don't understand why Map returns iterator makes code to fail

Time:12-24

I have some code that does:

map(lambda increment:
                 self.__delete_table_id_range(table, delete_field, value,
                                              delete_interval, increment),
                 range(delete_interval.min, delete_interval.max, self.purge_range))

In python 2 it works fine, but in python 3 I debugged and __delete_table_id_range function is never called.

I know that map returns now an iterator, so I changed the map to become a list with:

list(map(lambda increment:
                     self.__delete_table_id_range(table, delete_field, value,
                                                  delete_interval, increment),
                     range(delete_interval.min, delete_interval.max, self.purge_range)))

And only adding this the __delete_table_id_range function runs.

I don't understand why is this happening. Can somebody explains?

CodePudding user response:

map method return you an iterator that you can iterate with a classic for

my_list = [1, 2, 3]
result = map(lambda index: my_list[index] * 2, range(0, len(my_list), 1))
for index, element in enumerate(result):
    print(f"Element[{index}]: {element}")

You can do this, but I not recommend you

result = map(lambda increment: self.__delete_table_id_range(table, delete_field, value, delete_interval, increment), range(delete_interval.min, delete_interval.max, self.purge_range))
for element in result:
    pass

In your case I think it is better a classic for

for index in range(delete_interval.min, delete_interval.max, self.purge_range):
    self.__delete_table_id_range(table, delete_field, value, delete_interval, increment)
  • Related