comprehension syntax very common programming task is to produce one series of values based upon the processing of another series oftenthis task can be accomplished quite simply in python using what is known as comprehension syntax we begin by demonstrating list comprehensionas this was the first form to be supported by python its general form is as followsexpression for value in iterable if condition we note that both expression and condition may depend on valueand that the if-clause is optional the evaluation of the comprehension is logically equivalent to the following traditional control structure for computing resulting listresult for value in iterableif conditionresult append(expressionas concrete examplea list of the squares of the numbers from to nthat is [ ]can be created by traditional means as followssquares for in range( + )squares append( kwith list comprehensionthis logic is expressed as followssquares [ for in range( + )as second examplesection introduced the goal of producing list of factors for an integer that task is accomplished with the following list comprehensionfactors [ for in range( , + if = python supports similar comprehension syntaxes that respectively produce setgeneratoror dictionary we compare those syntaxes using our example for producing the squares of numbers for in range( + for in range( + for in range( + for in range( + list comprehension set comprehension generator comprehension dictionary comprehension the generator syntax is particularly attractive when results do not need to be stored in memory for exampleto compute the sum of the first squaresthe generator syntaxtotal sum( for in range( + ))is preferred to the use of an explicitly instantiated list comprehension as the parameter