Search code examples
pythonsimplifysimplification

Simplifying Lists


How Can This Code Be Simplified? That is the question.

    stat_keys.append(self.request.get("stat_one"))
    stat_keys.append(self.request.get("stat_two"))
    stat_keys.append(self.request.get("stat_three"))
    stat_keys.append(self.request.get("stat_four"))

Solution

  • stat_keys += [self.request.get(k) for k in ('stat_one', 'stat_two', 'stat_three', 'stat_four')]
    

    or

    stat_keys += map(self.request.get, ('stat_one', 'stat_two', 'stat_three', 'stat_four')))
    

    or

    map(stat_keys.append, map(self.request.get, ('stat_one', 'stat_two', 'stat_three', 'stat_four')))
    

    I suggest the first one, though.