Python One Line For Loop Lambda

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?

Python One Line For Loop Lambda

Example: Given an array a = [1, 2, 3, 4]. You need to create a second array b with all values of a—while adding +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 for and if statements.

The example [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 + ‘]’

List Comprehension

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>] 

A detailed tutorial on the topic is available for free at this tutorial on the Finxter blog.

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 x+y+z.

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.

Find the detailed article on lambda functions here.

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:

However, it would be better if you avoided the map function—it’s not readable and less efficient than list comprehension.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!