Ask Question, Ask an Expert

+61-413 786 465

info@mywordsolution.com

Ask Python Expert

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

 

Python, Programming

  • Category:- Python
  • Reference No.:- M9506005

Have any Question?


Related Questions in Python

A software company sells a package that retails for 99

A software company sells a package that retails for $99. Quantity discounts are given according to the following table: Quantity Discount 10 - 19 20% 20 - 49 30% 50 - 99 40% 100 or more 50% Write a program using python t ...

Question write a simple python program that takes use

Question: Write a simple python program that takes use inputs as non-zero digits and converts them into binary form. The response must be typed, single spaced, must be in times new roman font (size 12) and must follow th ...

Show times in tmus and seconds1 an associate grasps an oven

Show times in TMUs and seconds. 1. An associate grasps an oven door within reach and pulls it open 18 inches with the left hand (he does not relinquish control of the door). With a pan in the right hand, he carefully pos ...

Homework -this homework will have both a short written and

Homework - This homework will have, both a short written and coding assignment. The problems that are supposed to be written are clearly marked. 1) (Written) Make heuristics Describe two heuristics for the slide problem ...

Part i the assignment filesone of the most important

Part I: The Assignment Files One of the most important outcomes of this assignment is that you understand the importance of testing. This assignment will follow an iterative development cycle. That means you will write a ...

Tasksdemonstrate data scraping of a social network of

Tasks Demonstrate data scraping of a social network of choice. Develop technical documentation, including the development of the code & detailing the results. Provide a report on the findings, that includes research into ...

Assignment1 utilising python 3 build the following

Assignment 1. Utilising Python 3 Build the following regression models: - Decision Tree - Gradient Boosted Tree - Linear regression 2. Select a dataset (other than the example dataset given in section 3) and apply the De ...

Question why is software configuration management

Question : Why is software configuration management considered an umbrella activity in software engineering? Please include examples and supporting discussion. The response must be typed, single spaced, must be in times ...

Question write a python program with a graphical user

Question: Write a python program with a graphical user interface that will allow a user to create a custom pizza which they wish to order. At minimum, the user should be able to choose the size of the pizza, the type of ...

Architecture and system integrationcase study queensland

Architecture and System Integration Case Study: Queensland Health - eHealth Investment Strategy After evaluating various platforms, Queensland Health finally decided to adopt a Service Oriented Architecture (SOA) for its ...

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As