Comprehension Lists in Python

Comprehension lists

Comprehension lists in Python provide you a very concise and smart way of creating lists. In order to create a comprehension list you will use square brackets that would consist of a ‘for’ statement and it may or may not have more for or if statements.

For better understanding have a look at the following example:

numbers=[1,2,3,4,5,6,7,8,9,10]
even_numbers=[x for x in numbers if x%2==0]
for element in even_numbers:
    print(element)

Download the code Run the code

In the above example, even_number is a comprehension list. See how it is created from the numbers list.

Now , have a look at the second example. Here, we try to create list that provides squares of numbers that are given in the numbers list:

numbers=[1,2,3,4,5,6,7,8,9,10]
sq_of_numbers=[x*x for x in numbers]
for element in sq_of_numbers:
    print(element)

Download the code Run the code

Now, let’s try to produce a comprehension list that is a cross product of two lists

color=['red','blue','green']
dress=['frock', 'shirt','skirt']
color_of_dress=[(x,y) for x in color for y in dress]
for element in color_of_dress:
    print(element)

Have a look at the output. It has two for loops. For every x in colors it looks for every dress in y and then creates the sets.

Download the code Run the code

<<< Regular Expressions in Python – IIPython functions with multiple arguments >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .