KEMBAR78
Comprehension in Python | PDF | Language Arts & Discipline | Teaching Methods & Materials
0% found this document useful (0 votes)
307 views2 pages

Comprehension in Python

Comprehensions in Python allow for the concise construction of new sequences like lists, sets, and dictionaries from existing sequences. There are four types of comprehensions in Python: list comprehensions, dictionary comprehensions, set comprehensions, and generator comprehensions. List comprehensions provide an elegant way to create new lists using the syntax of an output expression followed by a for loop iterating over an input list, optionally including an if condition to filter the values.

Uploaded by

Sagar Kusekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
307 views2 pages

Comprehension in Python

Comprehensions in Python allow for the concise construction of new sequences like lists, sets, and dictionaries from existing sequences. There are four types of comprehensions in Python: list comprehensions, dictionary comprehensions, set comprehensions, and generator comprehensions. List comprehensions provide an elegant way to create new lists using the syntax of an output expression followed by a for loop iterating over an input list, optionally including an if condition to filter the values.

Uploaded by

Sagar Kusekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Comprehensions in Python

Comprehensions in Python provide us with a short and concise way to construct


new sequences (such as lists, set, dictionary etc.) using sequences which have been
already defined. Python supports the following 4 types of comprehensions:
 List Comprehensions
 Dictionary Comprehensions
 Set Comprehensions
 Generator Comprehensions

List Comprehensions:- List Comprehensions provide an elegant way to create new


lists. The following is the basic structure of a list comprehension:

Syntax:-
output_list = [output_exp for var in input_list if (var satisfies this condition)]

Note that list comprehension may or may not contain an if condition. List
comprehensions can contain multiple for (nested list comprehensions).

Example : Suppose we want to create an output list which contains only the even
numbers which are present in the input list. Let’s see how to do this using for
loops and list comprehension and decide which method suits better.

You might also like