Module 1 · Python crash course · Lesson 7 of 66
Functions, lambda, map and filter
Package code under a name, and apply it to whole lists.
In this lesson · about 14 minutes
- Write functions with parameters, defaults and return
- Write a short lambda
- Apply a function to a list with map and filter
A function packages code under a name. def starts it, the parameters go in parentheses, and return sends a result back. A parameter can have a default used when the caller leaves it out. A string right under the def line is a docstring that explains the function.
lambda, map and filter
A lambda is a tiny one-line function with no name: lambda var: var * 2 is the same as a function that returns var * 2. They're handy to pass into other functions:
map(func, seq)appliesfuncto every item.filter(func, seq)keeps the items wherefuncreturns True.
Both give back a lazy object, so wrap them in list() to see the result. You'll use this same idea constantly in pandas with .apply().
Exercise
Get the email domain
Write a function domainGet(email) that returns the website domain from an address like user@domain.com. Passing "user@domain.com" should return "domain.com".
Exercise
Words that start with s
Use filter() and a lambda to keep only the words that start with the letter s. The result should be ['soup', 'salad'].
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.