Press "Enter" to skip to content

Python Notes 6 : List Comprehensions & lambda Expressions

List Comprehensions

List Comprehensions allows us to build list objects using different notations.

  • list_1 = [x for x in ‘word’]
    • list_1 = [‘w’,’o’,’r’,’d’]
  • list_2 = [x**2 for x in range(0,11)]
    • list_2 = [0,1,4,9,16,25,36,49,64,81,100]
  • list_3 = [x for x in range(0,11) if x%2==0]
    • list_3 = [0,2,4,6,8,10]
  • list_4 = [x**2 for x in [x**2 for x in range(0,11)]]
    • list_4 = [0,1,16,81,256,625,1296,2401,4096,6561,10000]

Lambda Expression

Lambda expressions is an alternate way of creating functions in python. lambda’s body is a single expression, not a block of statements.

  • reverse_String = lambda str:str[::-1]
    • Above expression returns a reverse string
  • adder = lambda x,y:x+y
    • Above expression returns an added value

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *