List comprehensions, Python Programming

List Comprehensions


Python has a very nice built-in  facility for doing  many  iterative methods, known as list comprehensions. The basic template is




[ for in if ]

where is a single variable (or a tuple of variables), is a relation that evalu­ ates to a list, tuple,  or string, and is an expression that may use the variable . The if is optional; if it is showing, then only those variables  of


for which that expression is True are included in the resulting computation.


You can view  a list comprehension as a special  notation for a specific, very  general, class of

for loops.  It is equivalent to the following:


*resultVar* = []

for in :

if :




We used a kind of funny notation *resultVar* to indicate that there is some anonymous list that is getting built  up  during the evaluation of the list comprehension, but  we have  no perfect way  of taking  it. The output  is a list, which  is obtained by successively binding to elements of the result  of evaluating , testing  to see whether they  meet  a situation, and  if they fulfil the condition, calculating and collecting  the results into a list.


Whew.  It is probably easier to understand it by example.


>>> [x/2.0 for x in [4, 5, 6]]

[2.0, 2.5, 3.0]

>>> [y**2 + 3 for y in [1, 10, 1000]]

[4, 103, 1000003]

>>> [a[0] for a in [['Nal', 'Morty'],['Jacob','White'],

['Leslie','Kaelbling']]] ['Nal', 'Jacob', 'Leslie']

>>> [a[0]+'!' for a in [['Nal', 'Morty'],['Jacob','White'], ['Leslie','Kaelbling']]]

['Nal!', 'Jacob!', 'Leslie!']


Imagine that you have a list of numbers and you want  to construct a list containing just the ones that are not even.  You may  write


>>> nums = [1, 2, 5, 6, 88, 99, 101, 10000, 100, 37, 101]

>>> [x for x in nums if x%2==1]

[1, 5, 99, 101, 37, 101]


Note the use of the if and else condition here to add only particular values  of x.

And, of course, you can combine this with the other abilities of list comprehensions, to, for code, give the squares of the odd  numbers:


>>> [x*x for x in nums if x%2==1]

[1, 25, 9801, 10201, 1369, 10201]


You can also take structured statements in list comprehensions


>>> [first for (first, last) in [['Nal', 'Morty'],['Rose','Red'], ['Leslie','Kaelbling']]]

['Nal', 'Rose', 'Leslie']

>>> [first+last for (first, last) in [['Nal', 'Morty'],['Rose','Red'],


['NalMorty', 'RoseRed', 'LeslieKaelbling']


Another built-in  function that is useful  with list comprehensions is zip. Here are some codes of how it works:


> zip([1, 2, 3],[4, 5, 6])

[(1, 4), (2, 5), (3, 6)]

> zip([1,2], [3, 4], [5, 6])

[(1, 3, 5), (2, 4, 6)]


Here is an example of using  zip with a list comprehension:


>>> [first+last for (first, last) in zip(['Nal', 'Rose', 'Leslie'],


['NalMorty', 'RoseRed', 'LeslieKaelbling']

Note that this last program is very different from this one:

>>> [first+last for first in ['Nal', 'Rose', 'Leslie'] \

for last in ['Morty','Red','Kaelbling']]

['NalMorty', 'NalRed', 'NalKaelbling', 'RoseMorty', 'RoseRed',

'RoseKaelbling', 'LeslieMorty', 'LeslieRed', 'LeslieKaelbling']


Nested list comprehensions behave like nested for loop structure,  the expression in the structure comprehension is calculated for every combination of the values  of the variables


Posted Date: 8/9/2012 7:21:13 AM | Location : United States

Related Discussions:- List comprehensions, Assignment Help, Ask Question on List comprehensions, Get Answer, Expert's Help, List comprehensions Discussions

Write discussion on List comprehensions
Your posts are moderated
Related Questions
Modules As you start to write larger programs, you will want  to save the function de?nitions in multiple ?les, collected together according to what  they  do.  So, for exampl

program on damped lcr cicuit

You should use for whenever you can, because  it creates  the structure of your  loops clear. Sometimes, however, you require to do an operation various times, but you don't want t

#que Write a program that will take price data for stocks and print it graphically to the screen. Your program should begin by asking the user for the file name. It should then cre

#Why can''t I cd my Desktop? A minute ago I would open up cmd and it starts in C:\Users\myname but now it''s starting in C:\WINDOWS\system> and I don''t where I am or how to get ou

Expressions and assignment We can think of most computer programs as performing some sort of transformation on data.  Our code may get as input the exam scores of everyone in

Programs and Data Object-oriented programming is a popular way  of managing programs, which  groups together data  with  the procedures that  works on them,  thus  facilitatin

#ques Write the pseudocode (use a word processor please) and the Python 3.0 program for the following problem. A monkey is being fed some food. Read in the starting weight in lbs:o

Range Very frequently, we will want to iterate through a list of integer values, often as indices.  Python gives a useful function, range, which gives lists of integers. It ma

A program to count how many files are on the file system which displays summary information regarding the total number of bytes used by all files and a breakdown of the number of b