Thursday, January 18, 2018

List comprehension in Python

  • List comprehension is an elegant way to define and create list in Python. 
  • These lists have often the qualities of sets, but are not in all cases sets. 
  •  List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). 
  •  Syntax of list comprehension is easier to be grasped.
Function to convert Celsius values into Fahrenheit and vice versa. It looks like this with list comprehension:
>>> 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]
>>> 
Examples

No comments:

Post a Comment