Tuesday, October 14, 2008

List comprehensions in Python

Just came across this concept in the Django documentation, but without any background in Python or maths it wasn't immediately obvious what it was.

The basic syntax is:
L = [expression for variable in sequence]
L is the name of a the resulting variable containing the list of items generated by the loop
expression is the python expression that will be evaluated on each iteration of the for loop, using the given variable
variable refers to each item in the list to pass to the expression as we loop through it
sequence is the set of items we're looping through

An example:
toppings = ('ham', 'pineapple', 'beef', 'chicken')
x = ', '.join([toppings.loop_count() for t in toppings])
Totally pointless operation I know, as it simply copies the list in the 'toppings' variable to a new variable called 'x', but it illustrates the point! In reality it would make more sense if the initial list was a queryset object from a database that we want to loop through and list the values.

The for...in loop syntax already made sense to me, but I'd not come across this shorter way of writing it before. Apparently it's also the most efficient in terms of system resources.

No comments: