user2268507
user2268507

Reputation:

Two conditions in single line for loop

I have a function that has a return statement as follows:

x = 0
return{
    'restaurantList' : [restaurant.serializeGeneral(myArray[x]) for restaurant in self.restaurantList],
    'success' : self.success
    }

I need to increment x every time the for loop runs, however, I can't seem to get the syntax right.

Upvotes: 0

Views: 118

Answers (1)

CleverLikeAnOx
CleverLikeAnOx

Reputation: 1496

You can use the enumerate function to get both the index and value for each restaurant in the list as follows:

return {
    'restaurantList' : [restaurant.serializeGeneral(myArray[x]) for x, restaurant in enumerate(self.restaurantList)],
    'success' : self.success
}

You should probably just compute the list outside of a list comprehension because that line is way too long to be readable.

Upvotes: 1

Related Questions