Python

How to Implement List Comprehensions to Simplify Your Python Code

In Python, list comprehensions are a sophisticated and concise approach to generating lists. They can be used in a single line of code to filter, map, and decrease the iterations. List comprehensions create new lists through the use of an expression to every item in the current iterable (such as an list item, tuple item, or range item) and sometimes filtering the items depending on a condition. It can potentially improve the Python code readability and reduce the number of necessary lines.

Developers can choose one of the following syntaxes to implement:

Basic List Comprehension

[expression for an item in iterable if condition]

The following Python code shows two methods to produce an array of squares of integers that range from 1 to 5: a “for” loop and with a list comprehension approach.

Using a “For” Loop

for_squares_lc = []

for numb in range(1, 6):

  for_squares_lc.append(numb**2)

print(for_squares_lc)

This code generates an empty array called for_squares_lc. Then, it loops over the integers 1 through 5, squaring each one and adding it to the for_squares_lc. Finally, it outputs the for_squares_lc to the command prompt.

Using a List Comprehension

lc_squares_list = [numb**2 for numb in range(1, 6)]

print(lc_squares_list)

This code’s list comprehension loops through the numbers from 1 to 5, squaring each number, and stores it to the new list. Finally, the updated list is printed.

The two code pieces get the same result:

List comprehension, on the other hand, is briefer and more efficient. This is because the list comprehension doesn’t require the creation of an empty list and then appending to it. On the contrary, the list comprehension directly creates the new list.

List Comprehension with a Condition

new_list_comprehensions = [expression for item in iterable]

The result of evaluating the expression for every item within the iterable will be added into the new list. The condition is optional; if it is present, only the items for which the condition evaluates to True are included in the new list. For loops are a more traditional way to iterate over a list.

Example 1: Create and Print a List of All the Even Digits/Numbers from 1 to 20

evn_numbs_lc = [dnum for dnum in range(1, 21) if dnum % 2 == 0]

print("The Even numbers using comprehension: ", evn_numbs_lc)

evn_ls_for = []

for dnum in range(1, 21):

  if dnum % 2 == 0:

    evn_ls_for.append(dnum)

print("Using for loop: Here are Even Numbers", evn_ls_for)

Both code snippets produce the same output:

Example 2: Create a List of All the Vowels in a String

vowels_lc = [vowel for vowel in "Hello How are You?" if vowel in "aeiou"]

print("Vowels using list comprehension:", vowels_lc)

vowels_for = []

for vowel in "Hello How are You?":

  if vowel in "aeiou":

    vowels_for.append(vowel)

print("Vowels using for loop:", vowels_for)

For your reference, the outcome of the previously mentioned code is attached in the following:

Example 3: Create a List of All the Uppercase Letters in a String

uppercase_letters_lc = [letter for letter in "IPhone Apple Pro-Max" if letter.isupper()]

print("Uppercase letters using list comprehension:", uppercase_letters_lc)

uppercase_letters_for = []

for letter in "IPhone Apple Pro-Max":

  if letter.isupper():

    uppercase_letters_for.append(letter)

print("Uppercase letters using for loop:", uppercase_letters_for)

We included the result of the code that we added in this example:

Example 4: Create a List of All the Cubes of the Numbers from 1 to 5

cubes_lc = [cb * cb * cb for cb in range(1, 6)]

print("Cubes using list comprehension:", cubes_lc)

cubes_using_for = []

for cb in range(1, 6):

  cubes_using_for.append(cb * cb * cb)

print("Cubes using for loop:", cubes_using_for)

In the following instance, we incorporated the result of the code:

Example 5: Make a List of All the List Elements that Are Larger Than 5

greater_than_5_lc = [x for x in [10, 2, 7, 2, 5, 6, 0, 12, 9, 10] if x > 5]

print("Elements greater than 5 using list comprehension:", greater_than_5_lc)

greater_than_5_for = []

for x in [10, 2, 7, 2, 5, 6, 0, 12, 9, 10]:

  if x > 5:

  greater_than_5_for.append(x)
 
print("Elements greater than 5 using for loop:", greater_than_5_for)

Check out the output of this code here:

List Comprehension with an Else Clause

A list comprehension with an “else” clause allows the Python developer to specify a value to be included in the list if the condition is unmet. Here is the syntax for a list comprehension of the “if & else” statement:

[exp1 if condition else exp2 else exp3 for item in iterable]

If the condition evaluates to “True”, the expression following the “if” statement is assessed for each of the elements in the iterative, and the result of that evaluation is added to the new list. If the condition is not True or False, the expression after the “else” statement is evaluated, and the result is moved to the new list.

Example 1:

The function lists all files in the current or supplied directory with a “.py” extension or “no Python file” if the file name does not have a “.py” extension:

DisplayFileType.py:

import os

directory = r"E:\Work\Comprehension"

python_files = [pfileObj for pfileObj in os.listdir(directory) if pfileObj.endswith(".py")]

non_python_files = [pfileObj for pfileObj in os.listdir(directory) if not pfileObj.endswith(".py")]

print("Python files:")

print(python_files)

print("Non-Python files and directories:")

print(non_python_files)

Here’s the step-by-step explanation of the code:

  1. directory = “E:WorkComprehension”: The directory parameter specifies the directory path to be examined, with backslashes escaped using double backslashes or a raw string, particularly when working with Windows file paths.
  2. python_files = [file for file in os.listdir(directory) if pfileObj.endswith(“.py”)]:
    • In os.listdir(directory), a list of every single file and folder in the specified directory is retrieved.
    • The list comprehension [file for file in os.listdir(directory) if pfileObj.endswith(“.py”)] iterates over each item (file or directory) in the directory and filters out only those that end with “.py”. These are assumed to be Python files.
    • The filtered Python files are collected into the python_files list.
  3. non_python_files = [“no Python file” if file not in python_files else file for file in os.listdir(directory)]:
    • This list comprehension iterates over each item (file or directory) in the directory using os.listdir(directory).
    • For each item, it checks if it’s in the python_files list using the file, not in the python_files condition.
    • If the item is not in the python_files list (i.e., it’s not a Python file), it assigns the “no Python file” string to non_python_files. Otherwise, it includes the filename in non_python_files.
  4. print(python_files): This line prints the list of Python files in the specified directory.
  5. print(non_python_files): This line prints the list of non-Python files and directories that is found in the specified directory. If an item in the directory is not a Python file, it will be represented as “no Python file” in this list.

Here is the output of the file:

Example 2: Create a List of All the Prime Numbers from 1 to 20 or “Composite” If the Number is Composite

PrintPrime.py

import math as mth

primes_lc = [x if all(x % y != 0 for y in range(2, int(mth.sqrt(x)) + 1)) else "composite" for x in range(2, 21)]

print(primes_lc)

To see the output, open the command prompt using the Windows operating system and execute the code using the Python compiler. Here is the successful execution and printing of prime numbers on the screen:

This code works by creating an empty list called even_odd_loop. Then, it iterates over the numbers from 1 to 5, checking if each number is even or odd. If the number is even, the code appends the “Even” string to the even_odd_loop list. If the number is odd, the code appends the “Odd” string to the even_odd_loop list. Finally, the code prints the even_odd_loop list to the console. This code generates a list comprehension.

A list comprehension is a convenient way to build a new list from an iterable that already exists. The list comprehension in the following line of code iterates across the integers 1 to 5, evaluating the “Even’ if x% 2 == 0, else ‘Odd” expression. This expression’s result is then added to the new list. Finally, the code outputs the newly created list to the terminal.

OddEven.py:

even_odd_loop = []

for dnum in range(1, 6):

if dnum % 2 == 0:

even_odd_loop.append('Even')

else:

even_odd_loop.append('Odd')

print("Print Even Odd Numers using Loop: ",even_odd_loop)

even_odd_lc = ['Even' if dnum % 2 == 0 else 'Odd' for dnum in range(1, 6)]

print("Print Even Odd using List Comprehension: ",even_odd_lc)

Both of these code snippets produce the same output:

Conclusion

When used appropriately, the list comprehension can significantly simplify and increase the code readability. However, if you fail to make them too clever, the readability will suffer if they get too nested or intricate.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content