Comprehensions Examples

Forums » Python - Python > Comprehensions Examples
May 10, 2010 12:17:03 PM PDT (3 years ago). Seen 1,614 times. No replies.
Photo Ismail Ceylan
FQA Engineer
Financial Engines
Member since Apr 28, 2010
Forum Posts: 2
The Range() function can be used to create simple lists, however we usually need more complicated lists than what this function provides. The use of the Range() function is demonsrated below with some straightforward examples before we go on with List Comprehensions (some of the code is taken from the Marakana Python Training):

Code:
>>> help(range)
Help on built-in function range in module __builtin__:

range(...)
range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(3,10)
[3, 4, 5, 6, 7, 8, 9]
>>> range(3,10,2)
[3, 5, 7, 9]
>>> range(10,2,-1)
[10, 9, 8, 7, 6, 5, 4, 3]
>>> range(10,2,-3)
[10, 7, 4]


The syntax of the List Comprehensions is as follows:

[a_function_of_x for x in a_sequence]

The simplest case is when the function is a constant function of x which can be useful to create lists with equal elements:

Code:
>>> [0 for x in range(10)]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> [() for x in range(10)]
[(), (), (), (), (), (), (), (), (), ()]


We get more interesting results when the function is actually depends on the value of x. This can be a mathematical function as demonstrated below:

Code:
>>> [x**2 for x in range(8)]
[0, 1, 4, 9, 16, 25, 36, 49]
>>> [(x,x**2,x**3) for x in range(8)]
[(0, 0, 0), (1, 1, 1), (2, 4, 8), (3, 9, 27), (4, 16, 64), (5, 25, 125), (6, 36, 216), (7, 49, 343)]
[math.sin(x) for x in range(0,4*math.pi,math.pi/2)]
[0.0, 0.8414709848078965, 0.90929742682568171, 0.14112000805986721, -0.7568024953079282, -0.95892427466313845, -0.27941549819892586, 0.65698659871878906, 0.98935824662338179, 0.41211848524175659, -0.54402111088936977, -0.99999020655070348]


However, a function can be simply anything that produces a single output of any type. In the example below this list comprehension is used to create a list of playing cards in a deck:

Code:
"""lab08_2.py Use list comprehensions to make a deck of cards."""

def GetCards():
"""Return a deck of cards as a list of strings."""

values = [str(x) for x in range(2, 11)] + ['Jack','Queen','King','Ace']
suits = ('Clubs', 'Diamonds', 'Hearts', 'Spades')
deck = [v + ' of ' + s for s in suits for v in values] + ["Joker"] * 2
return deck

def main():
deck = GetCards()
print "The deck contains:"
for i, card in enumerate(deck):
if card is deck[-1]:
print 'and %s.' % card,
else:
print '%s, ' % card,
if i % 4 == 3:
print

if __name__ == '__main__':
main()
"""
$ lab08_2.py
The deck contains:
2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs,
6 of Clubs, 7 of Clubs, 8 of Clubs, 9 of Clubs,
10 of Clubs, Jack of Clubs, Queen of Clubs, King of Clubs,
Ace of Clubs, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds,
5 of Diamonds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds,
9 of Diamonds, 10 of Diamonds, Jack of Diamonds, Queen of Diamonds,
King of Diamonds, Ace of Diamonds, 2 of Hearts, 3 of Hearts,
4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts,
8 of Hearts, 9 of Hearts, 10 of Hearts, Jack of Hearts,
Queen of Hearts, King of Hearts, Ace of Hearts, 2 of Spades,
3 of Spades, 4 of Spades, 5 of Spades, 6 of Spades,
7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades,
Jack of Spades, Queen of Spades, King of Spades, Ace of Spades,
Joker, and Joker.
$
"""


The line "[v + ' of ' + s for s in suits for v in values]" creates the strings that represents the playing cards one a at time and stores it within a list. Note that it is possible to use multiple sequences when necessary.
Edited one time. Last edit by Ismail Ceylan on Jun 14, 2010 at 9:26:59 AM (about one year ago).