Posts

Showing posts with the label generator comprehension

What is list comprehension? Also explain generator comprehension, set comprehension and dictionary comprehension?

List Comprehension : List comprehension was introduced in 2.0. List comprehension is an elegant way to define and create a list in Python. List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). >>> Celsius = [39.2, 36.5, 37.3, 37.8] >>> Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ] >>> print Fahrenheit [102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999] Generator Comprehension : Generator comprehensions were introduced with Python 2.6.  They are simply a generator expression with a parenthesis - round brackets - around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list. >>> x = (x **2 for x in range(20)) >>> print(x) at 0xb7307aa4> >>> x = list(x) >>> print(x) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 10