List comprehensions, Python Programming

Assignment Help:

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 :

*resultVar*.append()

*resultVar*

 

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'],

['Leslie','Kaelbling']]]

['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'],

['Morty','Red','Kaelbling'])]

['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

 


Related Discussions:- List comprehensions

Random Geometric Graphs, Displaying random geometric graphs in an uniform s...

Displaying random geometric graphs in an uniform square, unit disk, dense rim unit disk, and uniform sphere

Python-models, Models It is a new system that is considerably easier th...

Models It is a new system that is considerably easier than  the system being modelled, but which saves the important points of the original machine. We might create a physical

Python programs, Python programs Every  general-purpose computer has a...

Python programs Every  general-purpose computer has a various detailed design, which  defines  that  the way  its program requires  to be specified is different. The "machine

Common errors and messages, Common Errors and Messages Here are some co...

Common Errors and Messages Here are some common Python errors  and error  messages to look  out for. Please let us give if you have any favorite additions for this list.

corse information, write a program that creates s dictionary containing co...

write a program that creates s dictionary containing course

Lists, simple program using list

simple program using list

Algorithm, given number isprime number or not

given number isprime number or not

Create a program to produce a business speak phrase, The goal of this exerc...

The goal of this exercise is to write a \business phrase" generator, which each time it is called produces lines of business speak, such as: It's time that we became uber-effici

Procedure calls, Procedure calls When you compute an expression of the...

Procedure calls When you compute an expression of the form ( ,  ..., )   the Python interpreter treats  this as a procedure call. It will be simpler to talk about

Write Your Message!

Captcha
Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd