Problem: Given a collection. You want to create a new list based on all values in this collection. The code should run in a single line of code. How do you accomplish this? Do you need a lambda function?
Example: Given an array
a = [1, 2, 3, 4]. You need to create a second array
b with all values of
+1 to each value. Here’s your multi-liner:
a = [1, 2, 3, 4] b =  for x in a: b.append(x+1) print(b) # [2, 3, 4, 5]
How do you accomplish this in a single line of code?
Answer: No, you don’t need a lambda function. What you’re looking for is a feature called list comprehension. Here’s the one-liner expression that accomplishes this without the lambda function:
b = [x+1 for x in a] print(b) # [2, 3, 4, 5]
You can try this example yourself in our interactive code shell:
Let’s dive into some background information in case you wonder how list comprehensions work. Based on your question, I also suspect that you don’t completely understand lambda functions either, so I’ll also add another section about lambda functions. Finally, you’ll also learn about a third alternative method to solve this exact problem by using the lambda function in combination with Python’s built-in map() function!
So, stay with me—you’ll become a better coder in the process! 🙂
List Comprehension 101
List comprehension is a compact way of creating lists. The simple formula is
[expression + context].
- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of
[x for x in range(3)] creates the list
[0, 1, 2].
Have a look at the following interactive code snippet—can you figure out what’s printed to the shell? Go ahead and click “Run” to see what happens in the code:
I’ll explain both ways of generating a new list in the following.
Example: Say you want to filter out all customers from your database who earn more than $1,000,000. This is what a newbie not knowing list comprehension would do:
# (name, $-income) customers = [("John", 240000), ("Alice", 120000), ("Ann", 1100000), ("Zach", 44000)] # your high-value customers earning <$1M whales =  for customer, income in customers: if income>1000000: whales.append(customer) print(whales) # ['Ann']
This snippet needs four lines just to create a list of high-value customers (whales)!
Instead, a much better way of doing the same thing is to use list comprehension:
whales = [x for x,y in customers if y>1000000] print(whales) # ['Ann']
List comprehension is dead simple when you know the formula.
“A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.”Official Python Documentation
Here is the formula for list comprehension. That’s the one thing you should take home from this tutorial.
Formula: List comprehension consists of two parts.
‘[‘ + expression + context + ‘]’
The first part is the expression. In the example above it was the variable
x. But you can also use a more complex expression such as
x.upper(). Use any variable in your expression that you have defined in the context within a loop statement. See this example:
whales = [x.upper() for x,y in customers if y>1000000] print(whales) # ['ANN']
The second part is the context. The context consists of an arbitrary number of for and if clauses. The single goal of the context is to define (or restrict) the sequence of elements on which we want to apply the expression. That’s why you sometimes see complex restrictions such as this:
small_fishes = [x + str(y) for x,y in customers if y<1000000 if x!='John'] # (John is not a small fish...) print(small_fishes) # ['Alice120000', 'Zach44000']
Albrecht, one of the loyal readers of my “Coffee Break Python” email course, pointed out that you can break the formula further down using the following blueprint:
lst = [<expression> for <item> in <collection> if <expression>]
Lambda Function 101
A lambda function is an anonymous function in Python. It starts with the keyword
lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example,
lambda x, y, z: x+y+z would calculate the sum of the three argument values
Here’s a practical example where lambda functions are used to generate an incrementor function:
Exercise: Add another parameter to the lambda function!
Watch the video or read the article to learn about lambda functions in Python:
Puzzle. Here’s a small code puzzle to test your skills:
def make_incrementor(n): return lambda x: x + n f = make_incrementor(42) print(f(0)) print(f(1))
To test your understanding, you can solve this exact code puzzle with the topic “lambda functions in Python” at my Finxter code puzzle app.
Alternative Method 3: map() + lambda + list()
Interestingly, there’s a third way of solving the above problem by using the
map() function (and the lambda function):
# Method 3: map() + lambda + list() a = [1, 2, 3, 4] b = list(map(lambda x: x+1, a)) print(b) # [2, 3, 4, 5]
You can learn about the
map() function in my video tutorial here:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.