Lambda/Anonymous Function Equivalence?


#1



https://www.codecademy.com/en/courses/python-beginner-en-KAgt5/3/1?curriculum_id=4f89dab3d788890003000096

So in this lesson it says that the line

lambda x: x % 3 == 0


Is equivalent to

def by_three(x):
    return x % 3 == 0

Which struck me as odd because nothing in that function addresses the individual elements of the list. So I tried it and typed

def by_three(x):
    return x % 3 == 0
    
print by_three(my_list)

But as I expected I got an error message

Traceback (most recent call last):
  File "python", line 8, in <module>
  File "python", line 6, in by_three
TypeError: unsupported operand type(s) for %: 'list' and 'int'

so what's missing here?


#2

Your by_three function takes a number, not a list.

Where anonymous functions come in handy in in expressions where calling an external function would be kind of clunky...

>>> print (list(filter(lambda x: not (x % 3), range(100))))
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
>>>

They're also handy when we want to have a single function name but assign the function to it conditionally.

>>> from random import randint
>>> a = randint(0, 100)
>>> if a > 49:
    f = lambda x: x ** 2
else:
    f = lambda x: x ** 3

    
>>> f(a)
50653
>>>

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.