[BangPypers] Comprehending the comprehensions
Anand Balachandran Pillai
abpillai at gmail.com
Mon Feb 9 07:39:46 CET 2009
Python 3.0 introduces two new ways of "comprehending".
We had list comprehensions before. Now there are set &
dict comprehensions in the language.
Let us say there are two lists. For generating the list of unique
products of numbers in the list, in Python 2.x, this could be
done in 2 approaches.
1. Using a set,
>>> l=[1,2,3,4]
>>> m=[3,4,5,6]
>>> set([x*y for x in l for y in m])
{3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24}
2. Using a dictionary and inserting the values as keys,
>>> l=[1,2,3,4]
>>> m=[3,4,5,6]
>>> d = {}
>>> [d.setdefault(x*y, 0) for x in l for y in m]
>>> d.keys()
[3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
>>>
In Python 3.0, this is straight-forward using "set comprehensions".
Set comprehensions are like list comprehensions but with braces replacing
the square brackets. And they produce sets, not lists.
So the approach (1) in py3k is a one-liner.
>>> {x*y for x in l for y in m}
{3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24}
The approach (2) is also possible, since we now have "dict comprehensions"
too! Which means you can build a dict in place without having to define one
before and using 'setdefault' etc.
>>> d={x*y:0 for x in l for y in m}
>>> list(d.keys())
[3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
Note that the (list(d.keys)) is needed in Py3k since d.keys() no longer
return a list as it used to in Py 2.x, but instead returns a generator.
Regards,
--Anand
--
-Anand
More information about the BangPypers
mailing list