Skip to content
Advertisement

How can I use map operator with for loop?

I have a function that returns a list of the total counts. I want to use the map but don’t know how I can use it.

Here is my function:

def get_bought_passenger_count(self):
    c = 0
    for book in self.bookings.all():
        c += book.passenger_count
    return c

I want to use this with the map.

Advertisement

Answer

I don’t think it’s neccessary.

you are just constantly adding terms, so it’s just a sum and it doesn’t require to use the map() function, you could use the builtin sum() function, and a generator:

def get_bought_passengers(self):
    return sum(book.passenger_count for book in self.bookings.all())

as @Lecdi said in the comments.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement