Understanding List Comprehensions in Python



List comprehensions provide a succinct and readable way to generate lists. They condense a for loop and the creation of a new list into a single line of code. This not only saves space but also enhances code clarity.

 

Basic Syntax

 

The general syntax of list comprehension is as follows:

new_list = [expression for item in iterable if condition]

Here's a breakdown of the components:

expression: The operation to be performed on each item in the iterable.

item: Represents the current item in the iterable.

iterable: The collection of items to be processed.

condition (optional): A filter to include only specific items that meet the given condition.

 

Examples of List Comprehensions

 

Let's explore some practical examples to better understand list comprehensions.

 

Example 1: Squaring Numbers

 

# Using a loop

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

squared = []

for num in numbers:

    squared.append(num ** 2)

print(squared)


# Using a list comprehension

squared = [num ** 2 for num in numbers]

print(squared)

Output

# Using a loop
[1, 4, 9, 16, 25]

# Using a list comprehension
[1, 4, 9, 16, 25]

 

Example 2: Filtering Odd Numbers

 

# Using a loop

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

odd_numbers = []

for num in numbers:

    if num % 2 != 0:

        odd_numbers.append(num)

print(odd_numbers)



# Using a list comprehension

odd_numbers = [num for num in numbers if num % 2 != 0]

print(odd_numbers)

Output

# Using a loop
[1, 3, 5]


# Using a list comprehension
[1, 3, 5]

 

Example 3: Palindrome Check

 

#Using Loop

words = ["radar", "python", "level", "hello"]

palindromes = []

for word in words:

    if word == word[::-1]:

        palindromes.append(word)

print(palindromes)





#Using a list comprehension

words = ["radar", "python", "level", "hello"]

palindromes = [word for word in words if word == word[::-1]]

print(palindromes)

Output

['radar', 'level'] # Using loop
['radar', 'level'] # Using list comprehension

 

Example 4 : Extracting Initials From Names

 

names = ["John Smith", "Alice Johnson", "Bob Brown"]

# Using list comprehension to extract initials
initials = [name.split()[0][0] + name.split()[1][0] for name in names]

print(initials)

Output

['JS', 'AJ', 'BB']

 

Example 5 : Filtering and Mapping

 

#using list comprehension

grades = [85, 92, 78, 90, 88, 95, 72, 60]

passing_grades = [grade for grade in grades if grade >= 75]

letter_grades = ['A' if grade >= 90 else 'B' if grade >= 80 else 'C' for grade in grades]

print(passing_grades)

print(letter_grades)

Output

[85, 92, 78, 90, 88, 95]
['B', 'A', 'C', 'A', 'B', 'A', 'C', 'C']

 

Advantages of List Comprehensions

 

1. Readability

List comprehensions allow you to express complex operations in a clear and concise manner. This makes your code more readable and easier to understand for both you and fellow developers.

 

2. Reduced Code Size

By encapsulating the loop and list creation into a single line, list comprehensions help reduce the overall size of your codebase.

 

3. Performance

In many cases, list comprehensions are more efficient than traditional loops, as they are optimized for speed.

 

Nested List Comprehensions

 

Just as you can nest loops, you can also nest list comprehensions. This enables you to work with multi-dimensional data structures.

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

flattened = [num for row in matrix for num in row]

 

Problem: String Expansion

Given a list of strings, write a program that expands each string by duplicating each character using nested list comprehensions.

For example, if the input list is input_strings = ["abc", "def", "xyz"]

The output should be :

expanded_strings = [['a', 'a', 'b', 'b', 'c', 'c'],

                                  ['d', 'd', 'e', 'e', 'f', 'f'],

                                  ['x', 'x', 'y', 'y', 'z', 'z']]

 

Solution using nested list comprehensions:
input_strings = ["abc", "def", "xyz"]


expanded_strings = [[char for char in string for _ in range(2)] for string in input_strings]


for expanded in expanded_strings:

    print(expanded)

Output

['a', 'a', 'b', 'b', 'c', 'c']
['d', 'd', 'e', 'e', 'f', 'f']
['x', 'x', 'y', 'y', 'z', 'z']

 

Summary

 

List comprehensions stand as a testament to Python's elegance and efficiency. By mastering this technique, you equip yourself with a versatile tool to create, manipulate, and filter lists



Thanks for feedback.



Read More....
Arrays and Lists in Python
Python Iterators
Lambda or Anonymous Functions in Python
Most common built-in methods in Python
Python Decorators
Python Dictionaries