0% found this document useful (0 votes)
32 views

How To Write Efficient Python Code - Engineering Education (EngEd) Program - Section

The document provides an overview of techniques for writing efficient Python code, including list comprehension, lambda functions, and functions like map, filter, and reduce. It begins by explaining list comprehension as a way to generate lists with a single line of code compared to traditional loops. Next, it covers lambda functions as a way to write small anonymous functions in one line. Finally, it discusses how functions like map, filter, and reduce can be used to manipulate lists in Python in an efficient manner. The overall goal is to equip readers with tools to improve their productivity as Python developers.

Uploaded by

Ubaid PATAVEGAR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

How To Write Efficient Python Code - Engineering Education (EngEd) Program - Section

The document provides an overview of techniques for writing efficient Python code, including list comprehension, lambda functions, and functions like map, filter, and reduce. It begins by explaining list comprehension as a way to generate lists with a single line of code compared to traditional loops. Next, it covers lambda functions as a way to write small anonymous functions in one line. Finally, it discusses how functions like map, filter, and reduce can be used to manipulate lists in Python in an efficient manner. The overall goal is to equip readers with tools to improve their productivity as Python developers.

Uploaded by

Ubaid PATAVEGAR
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

EngEd Community
Section’s Engineering Education (EngEd) Program fosters a community of university students in Computer
Science related fields of study to research and share topics that are relevant to engineers in the modern
technology landscape. You can find more information and program guidelines in the GitHub repository. If you're
currently enrolled in a Computer Science related field of study and are interested in participating in the
program, please complete this form
.

How to write efficient Python


code
June 21, 2021
Topics: Languages

As a beginner programmer, writing efficient python code is not


the main goal but rather to learn the basic syntax, the flow of the
language, and how to think like a programmer. But things get
interesting when you are trying to advance to an intermediate-
level developer and become a true nerd, no pun intended.

Writing efficient python code is one way a beginner programmer can


advance to become an intermediate programmer and appreciate code
readability coupled with the productivity of a developer.

This tutorial is focused on teaching you how to write efficient python


code. By the end of this tutorial, you will be equipped with the tools
needed to improve your productivity as a developer. Tools we would use
include list comprehension, lambda, etc.
https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 1/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

Prerequisites

To follow along with this tutorial, a basic understanding of python is


required. And a python interpreter should be installed in your local
environment.

List comprehension

List comprehension is a technique of creating a list containing data


with a single line of code. It’s common in various programming
languages, including Python.

Let’s go over the syntax of list comprehension:

result = [transform iteration filter]

The result would be the final list containing our data, the transform is
the value of each data in our list, it keeps on changing as the value of
the iterator changes. The iteration is a loop that helps populate our list
with the required amount of data. Finally, the filter (optional) is used to
filter out the data that we don’t want.

Before we take a look at an example of list comprehension, let’s take a


look at the traditional way of generating a list with data so we can
compare the two ways:

nums = []

for x in range(10):

nums.append(x)

print(nums)

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 2/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

It took us about 3 lines of code. Let’s try to be more efficient using list
comprehension:

nums = [x for x in range(10)]

print(nums)

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Voilà, just one line of code to achieve the earlier result. It is way quicker
to write once you understand the syntax and flow of list comprehension.

Let’s take a look at two more complex examples by adding filters:

nums = [x for x in range(20) if x % 2 != 0]

print(nums)

Output:

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 3/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Another example:

nums = ['True' if x % 2 == 0 else 'False' for x in range(10)]

print(nums)

Output:

['True', 'False', 'True', 'False', 'True', 'False', 'True', 'False', 'T

With these two examples above, we added the ability to use the if/else
statement in our list comprehension. It should be noted that the elif
statement can’t be used within list comprehension.

In this section, we learned about using list comprehension to generate


a list with data. In the next section, we will take a look at lambda
functions.

Lambda functions

Lambda functions is a technique in Python to write our functions on a


single line. They are regarded as anonymous (nameless) functions. They
are also not suited for complex functions. Just like with list
comprehension, they make our code small and concise.

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 4/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

Let’s take a look at the syntax:

lambda arguments: expression

The value at the left is referred to as the arguments, while the values at
the right are the expression. Let’s break the syntax further:

lambda arguments: value_to_return if condition else value_to_return

Before we take a look at an example of lambda functions, let’s take a


look at an example of a regular function in Python so we can compare
the two ways:

def even_or_odd(n):

if n % 2 == 0:

return "Even"

else:

return "Odd"

print(even_or_odd(10))

Output:

Even

This took us about five lines of code to write, with lambdas I’m happy to
say that it’ll only take one line:

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 5/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

print((lambda n: "Even" if n % 2 == 0 else "Odd")(9))

Output:

Odd

We can also store them inside variables:

even_or_odd = lambda n: "Even" if n % 2 == 0 else "Odd"

even_or_odd(8)

Output:

Even

If we store them inside a variable, we don’t need to wrap parenthesis


around the lambda function and the argument. The variable serves as the
identifier to call the function.

In this section, we looked at lambdas which is a very quick way of writing


a function. They don’t work well for very complex functions. In the next
section, we’ll take a look at three very useful functions named map,
filter, and reduce.

Map, Filter and Reduce


https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 6/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

When you are working with a list filled with data, map, filter, and reduce
give you the ability to perform common list manipulation tasks.

The first on the list is map. With the map function we can modify our list
however we want.

Let’s take a look at an example:

# Example of a map function

nums = [1, 2, 3, 4, 5]

squared_nums = list(map(lambda x: x * x, nums))

print(squared_nums)

Output:

[1, 4, 9, 16, 25]

The map function takes two arguments, the function that would modify
the data, and the data itself. In our example, we used the lambda
function but we can use it without lambdas.

The map function coupled with the lambda function allows us to modify
our list with just one line of code.

Note that we used the list function to convert map objects back to a
list.

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 7/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

The second one is filter, the filter function is used to filter out
unwanted data from our list.

Let’s take a look at an example:

# Example of a filter function

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_nums = list(filter(lambda x: True if x % 2 == 0 else False, nums))


print(even_nums)

Output:

[2, 4, 6, 8, 10]

In our example, we are filtering out the odd numbers.

The reduce function helps to reduce the items in our list to just one
value.

Let’s take a look at an example:

# Example of a reduce function

from functools import reduce

nums = [5 ,6 , 7 ,8 , 9, 10]

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 8/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

sum_of_nums = reduce(lambda a,b: a + b, nums)

print(sum_of_nums)

Output:

45

In our example, we used the reduce function to add up all the data in our
list.

Note that we have to import reduce from functools before we can use it.

The map, filter, and reduce save us time from creating our list
manipulation function. They are useful for many common cases.

Conclusion

I am glad that you have reached the end of this article, I encourage you
to use the concepts you have been introduced within your next Python
project and check out how it improves your efficiency as a developer.

Happy coding!

Peer Review Contributions by: Mohan Raj

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 9/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

Did you find this article helpful?

0 Comments Sort By Best 

The EngEd community is subject to Section's moderation policy.

Be the first to comment... LOGIN SIGNUP

Similar Articles

Languages, Node.js

Building a Payroll System with Next.js

Read More

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 10/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

Languages

Creating and Utilizing Decorators in Django

Read More

Languages

Creating a Simple Denoising App

Read More

EngEd Author Bio

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 11/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

Samuel Torimiro
Samuel Torimiro is enthusiastic about software engineering, teaching and entrepreneurship. His
goal is to build web and mobile applications to better serve hundreds of millions of customers.

View author's full profile

Join our Slack community

Add to Slack

Company

About

Careers WE'RE HIRING

Legals

Resources

Blog

Edge Content Library

Solution Briefs

Engineering Education

Pricing

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 12/13
8/16/22, 12:51 PM How to write efficient Python code | Engineering Education (EngEd) Program | Section

Support

Docs

Community Slack

Help & Support

Release Notes

Platform Status

Contact Us

Section supports many open source projects including:

cloud native
varnish cache the linux lf edge
computing foundation
logo foundation logo logo
logo

© 2022 Section

Privacy Policy Terms of Service

https://www.section.io/engineering-education/how-to-write-efficient-python-code/ 13/13

You might also like