Count the Number of Exact Lines

We will learn how to count the number of lines in a file by ignoring the empty lines.

Removing empty lines

Here, we’ll learn how to write a piece of code that will remove all the empty lines.

We’ve written a piece of code that contains a for loop. This will remove all the lines that are empty.

for l in lines:
    if not l:
        lines.remove(l)

Let’s go over this line by line.

for l in lines:

We’re looping over our list lines. l will contain each line as Python is looping over them.

Note: If you come from a C/C++ background, you might be surprised that we’re not using arrays. We simply don’t need to!

Python will do that for us automatically. It will take the list lines and automatically loop over them. We don’t need to write lines[0], lines[1], lines[2], and so forth. In fact, doing so is an anti-pattern.

Now that we have each line, we need to check if it’s empty. There are many ways to do it. One is:

if len(l) == 0:

This checks if the current line has a length of 0. This works well, but there is a more elegant way:

if not l:
    lines.remove(l)

The not keyword in Python

The not keyword in Python will automatically check for emptiness. If the line is empty, we’ll remove it from the list using the remove() command.

Note: Like the for loop, we need to give four spaces to let Python know that this instruction is under the if condition.

The above lines of code have already been added into the code widget below for our ease.

Now we should have the correct number of lines when we add the above code in the coding widget below.

Get hands-on with 1400+ tech skills courses.