[Python-ideas] Adding list.pluck()

Mathias Panzenböck grosser.meister.morti at gmx.net
Sat Jun 2 17:54:50 CEST 2012

There are already at least two easy ways to do this:

 >>> stooges=[{'name': 'moe', 'age': 40}, {'name': 'larry', 'age': 50}, {'name': 'curly', 'age': 60}]
 >>> [guy['name'] for guy in stooges]
['moe', 'larry', 'curly']
 >>> from operator import itemgetter
 >>> map(itemgetter('name'),stooges)
['moe', 'larry', 'curly']

Also I'm used to such functions being called "collect" (Ruby) or "map" (Python, jQuery) and 
accepting a function/block as an argument. In Ruby-on-Rails it can be &:name as a shorthand for 
{|item| item[:name]}, which is equivalent to itemgetter('name') in Python. So if you insist of 
making it shorter (but less readable) you could do:

 >>> from operator import itemgetter as G
 >>> map(G('name'),stooges)
['moe', 'larry', 'curly']

On 06/01/2012 11:10 PM, Cenk Altı wrote:
> Hello All,
> pluck() is a beautiful function which is in underscore.js library.
> Described as "A convenient version of what is perhaps the most common
> use-case for map: extracting a list of property values."
> http://documentcloud.github.com/underscore/#pluck
> What about it implementing for python lists? And maybe for other iterables?

More information about the Python-ideas mailing list