Tuesday, July 31, 2018

Python 1. Lambda, list and dictionary comprehensions.

Lambda 

Lambda is a small anonymous function which can accept any number of arguments but can only have one expression:

>>> g = lambda a,b,c :  a**b - c # literally this means lambda accepts a, b and c variables, and returns "a**b-c"
>>> g
<function <lambda> at 0x7fe8640b5410>
>>> g(1,2,3) # 1**2 - 3 = 1 - 3 = -2
-2
>>>

List comprehension

>>> squares = [n**2 for n in range(10)] 
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = [ # more readable form of list comprehensions
... n**2 # like SQL SELECT
... for n in range(10) # like SQL FROM
... ]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares = [
... n**2 # SELECT
... for n in range(10) # FROM
... if n%2 == 0 # WHERE
... ]
>>> squares
[0, 4, 16, 36, 64]
>>> type(squares)
<type 'list'>
>>> letters = [letter for idx,letter in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ")]
>>> letters
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
>>> 

Dictionary comprehension

>>> test_dict = {index+1 : letter for index, letter in enumerate(letters)}
>>> test_dict
{1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I', 10: 'J', 11: 'K', 12: 'L', 13: 'M', 14: 'N', 15: 'O', 16: 'P', 17: 'Q', 18: 'R', 19: 'S', 20: 'T', 21: 'U', 22: 'V', 23: 'W', 24: 'X', 25: 'Y', 26: 'Z'}
>>> 

No comments:

Post a Comment