{ Lambdas and Dates. }

Objectives

By the end of this chapter, you should be able to:

  • Create and use lambdas
  • Manipulate dates and times using the datetime module

Lambdas

The closest we have to "anonymous" functions in Python is lambdas. Lambdas are useful if you want to write a function which can be described in a single line of code. Here are some examples:

add = lambda x,y: x + y
double = lambda val: 2 * val
yell = lambda str: str.upper() + "!!!"

add(1,2) # 3
double(5) # 10
yell("hello") # 'HELLO!!!'

add.__name__ # '<lambda>' 
add.__name__ == double.__name__ # True

Lambda functions start with the keyword lambda. Next comes a comma separated list of arguments, then a colon, then the expression you want the lambda to return. For simple one-line functions, lambdas can be a convenient shorthand for the traditional function definition. But these functions are anonymous; as you can see, they all share the same name.

One use case for lambdas is when you want to apply map, filter, or reduce (which as of Python 3 is part of the functools module). Here are some examples:

from functools import reduce
a = [1,2,3,4,5]

reduce(lambda x,y:x+y, a) # 15

list(map(lambda x:x*2, a)) # [2,4,6,8,10]
list(filter(lambda x:x*2 > 5, a)) # [3,4]

Dates + Times using the Datetime class

There is a quite a bit of functionality we have around dates and times with Python, but for now we'll stick to a few simple examples. Make sure you import the datetime module.

import datetime

# times
# hour, minute, second
t = datetime.time(1, 25, 10)
t.hour # 1
t.microsecond # 0 

datetime.time.min # 00:00:00

today = datetime.date.today()
today.timetuple() #namedtuple with data about date
today.day

When you're ready, move on to Generators, Iterators and Decorators Exercises

Continue

Creative Commons License