Reduce() and lambda functions
You're getting very good at using lambda functions! Here's one more function to add to your repertoire of skills. The reduce()
function is useful for performing some computation on a list and, unlike map()
and filter()
, returns a single value as a result. To use reduce()
, you must import it from the functools
module.
Remember gibberish()
from a few exercises back?
# Define gibberish
def gibberish(*args):
"""Concatenate strings in *args together."""
hodgepodge = ''
for word in args:
hodgepodge += word
return hodgepodge
gibberish()
simply takes a list of strings as an argument and returns, as a single-value result, the concatenation of all of these strings. In this exercise, you will replicate this functionality by using reduce()
and a lambda function that concatenates strings together.
This is a part of the course
“Introduction to Functions in Python”
Exercise instructions
- Import the
reduce
function from thefunctools
module. - In the
reduce()
call, pass a lambda function that takes two string argumentsitem1
anditem2
and concatenates them; also pass the list of strings,stark
. Assign the result toresult
. The first argument toreduce()
should be the lambda function and the second argument is the liststark
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import reduce from functools
# Create a list of strings: stark
stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon']
# Use reduce() to apply a lambda function over stark: result
result = reduce(____, ____)
# Print the result
print(result)
This exercise is part of the course
Introduction to Functions in Python
Learn the art of writing your own functions in Python, as well as key concepts like scoping and error handling.
Learn about lambda functions, which allow you to write functions quickly and on the fly. You'll also practice handling errors in your functions, which is an essential skill. Then, apply your new skills to answer data science questions.
Exercise 1: Lambda functionsExercise 2: Pop quiz on lambda functionsExercise 3: Writing a lambda function you already knowExercise 4: Map() and lambda functionsExercise 5: Filter() and lambda functionsExercise 6: Reduce() and lambda functionsExercise 7: Introduction to error handlingExercise 8: Pop quiz about errorsExercise 9: Error handling with try-exceptExercise 10: Error handling by raising an errorExercise 11: Bringing it all togetherExercise 12: Bringing it all together (1)Exercise 13: Bringing it all together (2)Exercise 14: Bringing it all together (3)Exercise 15: Bringing it all together: testing your error handling skillsWhat is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.