Increase the Readability of Your Python Script With 1 Simple Tool – Built In

One of the biggest challenges beginning programmers have when learning a new language is figuring out how to make their code more readable. Since collaboration is a critical part of the modern working world, its vital we ensure other people can easily understand and make use of our code. At the same time, beginning programmers are struggling to figure out how to make their code work, and figuring out how to make it user-friendly seems like an added hurdle you just dont have time for.

Ive been there, I get it.

Fortunately, there are some pretty simple steps you can take to write clearer code. One of the main ways to make Python code more readable is by collapsing multiple lines of code into a single line. There are many ways to do this so well dive into one particular method: list comprehensions. The best part about this process is, since this is a standard method, other Python programmers reviewing your code will be able to quickly understand what youre doing.

List comprehensions are a Python tool that allow you to create a new list by filtering the elements in your data set, transform the elements that pass the filter and save the resulting listall in a single line of code.

Clarify Your Code5 Ways to Write More Pythonic Code

List comprehensions are a tool that allow you to create a new list by filtering the elements in your data set, transformthe elements that pass the filter and save the resulting listall in a single line of code.

But before we dive into that, lets take a second to think about what code we have to write to accomplish that without list comprehensions.

First we need to create an empty list to fill later.

Then we need to write a for loop to iterate through each value in our data set.

Then we need to write an if statement to filter the data based on a condition.

And finally, we need to write another statement to append the resulting data into the list.

Lets take a look at the code to see what this looks like. Imagine we have a list of 10 numbers and we want to identify and save each number greater than the mean value.

That example code first creates a list called Numbers which contains our data set, then executes the four steps outlined above to create the resulting list. What do you think the result will be?

When youre ready to check your answer, here it is: [6, 7, 8, 9, 10].

This takes four lines of code. Four lines isnt an unmanageable amount of code but if you can write it in a single line that others easily understand, why not?

More on Python ListsHow to Append Lists in Python

The general structure of a list comprehension is as follows:

[Function for Value in DataSet if Condition]

Written in plain English, this says, Execute this Function on each Value in Data Set that meets a certain Condition.

Function is how you want to modify each piece of data, which you may not want to do! Modifications arent necessary and you can use list comprehensions to store values without modifying them.

Value is an iterator we use to keep track of the particular data value tracked on each pass through the for loop.

DataSet is the data set youre analyzing in the list comprehension.

Condition is the condition the data must meet to be included.

To map those terms to the code in our previous example, we have:

Function: Number. Since were only storing the data without modification we store the iterator without calling a function.

Value: Number. This is the iterator name we used in the previous example, so we use it again here. Note: For this example, the term used in Function and Value must be the same because our goal is to store Value.

DataSet: Numbers. This was the list we used as our data set in the previous example and were going to use it the same way here.

Condition: if Number > sum(Numbers)/len(Numbers). This if statement identifies numbers that are greater than the mean of the data set and instructs the list comprehension to pass those values.

Heres how it looks written as a single list comprehension:

The result from executing this code is [6, 7, 8, 9, 10]. Its the same result while written with a single line of code using a structure that other coders will easily understand.

Weve focused on lists but this method can be applied to dictionaries, too (FYI, if youre new to coding, you may see dictionary commonly abbreviated as dict.) We only need to make a few slight changes to the syntax that correspond to the different syntax used for those data structures.

The only difference between sets and lists, syntactically, is that sets use curly brackets instead of the square brackets we use for lists. A set comprehension looks like this:

Notice how there are only two differences here. Numbers with curly brackets instead of square brackets, which makes it a set instead of a list. We also surround the comprehension creating Result with curly brackets instead of square brackets, which makes it a set comprehension instead of a list comprehension. Thats it.

We get the same result in set form instead of list form: {6, 7, 8, 9, 10}.

Learn More With Peter GrantLearn the Fundamentals of Control Flow in Python

There are two differences between list comprehensions and dictionary comprehensions, both of which are driven by the requirements of dictionaries.

First, dictionaries use curly brackets instead of square brackets so the list comprehension structure must use curly brackets. Since this is the same requirement for set comprehensions, if you start by treating a dictionary like a set, youre halfway there.

The second difference is driven by the fact that dictionaries use key: value pairs instead of only values. As a result, you have to structure the code to use key: value pairs.

These two changes lead to a structure that looks like this:

This does yield a slightly different result, because now the output is a dictionary instead of a list or set. Dictionaries have both keys and values, so the output has both keys and values. This means that the output will be: {6: 6, 7: 7, 8: 8, 9: 9, 10:10}.

You may recall I said you can apply functions to these values as you process them. We havent done that yet but its worth taking a moment to consider it now.

So how do we go about applying functions? We simply add their description to the Function part of the code.

For example, if we want to calculate the square of values instead of simply returning the value we use the following code:

You could apply any number of other functions, making list comprehensions a flexible and powerful way to simplify your code.

Keep in mind the purpose of list comprehensions is to make your code easier to read. If your list comprehension makes it harder to read then it defeats the purpose. List comprehensions can become difficult to read if the function or the condition are too long. So, when youre writing list comprehensions keep that in mind and avoid them if you think your code will be more confusing with them than without them.

People learning a new programming language have enough of a challenge figuring out how to make their code work correctly, and often dont yet have the tools to make their code clear and easy to read. Nevertheless, effective collaboration is vital to the modern workplace. Its important we have the necessary tools to make our code readable to those without a coding background. List comprehensions are a standard Python tool you can use to make your code simpler to read and easier for your colleagues to understand.

This article was originally published on Python in Plain English.

Continued here:

Increase the Readability of Your Python Script With 1 Simple Tool - Built In

Related Post

Comments are closed.