top of page

Pythonic in AI - List Comprehension

  • Michael He
  • Oct 20
  • 3 min read
ree

The Python list comprehension is widely used in AI technique and involving 3 levels of comprehension -


  1. Basic comprehension (No Filter)


Standard for loop -

squares_list = []
for number in range(5):
    # Calculate the square
    square = number ** 2
    squares_list.append(square)
print(squares_list) 

# Output: [0, 1, 4, 9, 16]

List comprehension -

squares_list_comp = [number ** 2 for number in range(5)]
print(squares_list_comp) 

# Output: [0, 1, 4, 9, 16]



  1. Filtering Data


Example 1: start with as list of names and create a new list containing only the names that start with the letter 'J'.


Standard for loop -

names = ["Alice", "Bob", "Charlie", "Jane", "Joe"]
j_names = []

for name in names:
    if name.startswith('J'):
        j_names.append(name)
print(j_names)  

# Output: ['Jane', 'Joe']



List comprehension -


names = ["Alice", "Bob", "Charlie", "Jane", "Joe"]

j_names_l_com = [name for name in names if name.startswith('J')]
print(j_names_l_com)  

# Output: ['Jane', 'Joe']


Example 2: Returning a list with all even numbers b/w 1 and 10 inclusive, each multiple by 10


Standard for loop -


new_list = []

for n in range(1,11): 
    if n % 2 == 0:
        new_list.append(n * 10)
print(new_list) 

# Output: [20, 40, 60, 80, 100]


List comprehension -


print([num * 10 for num in range(1, 11) if num % 2 == 0])


Example 3: Returning a list that contains the element from range(1, 11) multiplied by 10 if the number is even, and "None" if that number is odd.


Standard for loop -


new_list = []

for num in range(1, 11):
    if num % 2 == 0:
        new_list.append(num * 10)
    else:
        new_list.append("None")
print(new_list) 

# Output: ['None', 20, 'None', 40, 'None', 60, 'None', 80, 'None', 100]



List comprehension -


print([num * 10 if num % 2 == 0 else "None" for num in range(1, 11)]) 

# Output: ['None', 20, 'None', 40, 'None', 60, 'None', 80, 'None', 100]



  1. Nested Loops



Example 1:


Standard for loop -


letters = ['a', 'b']
numbers = [1, 2, 3]
pairs = []

# Outer loop runs first (a, then b)
for letter in letters:
    # Inner loop runs completely for each letter (1, 2, 3)
    for number in numbers:
        pairs.append((letter, number))
print(pairs)  


# Output: [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]



List comprehension -


letters = ['a', 'b']
numbers = [1, 2, 3]

pairs_l_comp = [(letter, number) for letter in letters for number in numbers]
print(pairs_l_comp) 


# Output: [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]


Example 2:


List comprehension -


products_on_sale = ['Chair_Type_1', 'Chair_Type_2', 'Chair_Type_3', 'Chair_Type_4']
sale_prices = [100, 120, 135, 150]
quantities = [1000, 1500, 1300]

# Calculate total sales revenue for each combination of product, price, and quantity
sales_revenue = [[chair_type, price*quantity]   # List comprehension to calculate revenue  
                 for chair_type in products_on_sale # Iterate over each product
                    for price in sale_prices        # Iterate over each price
                        for quantity in quantities] # Iterate over each quantity
print(sales_revenue) # Output the sales revenue list

# Expected Output:

[['Chair_Type_1', 100000], ['Chair_Type_1', 150000], ['Chair_Type_1', 130000], ['Chair_Type_1', 120000], ['Chair_Type_1', 180000], ['Chair_Type_1', 156000], ['Chair_Type_1', 135000], ['Chair_Type_1', 202500], ['Chair_Type_1', 175500], ['Chair_Type_1', 150000], ['Chair_Type_1', 225000], ['Chair_Type_1', 195000], 

['Chair_Type_2', 100000], ['Chair_Type_2', 150000], ['Chair_Type_2', 130000], ['Chair_Type_2', 120000], ['Chair_Type_2', 180000], ['Chair_Type_2', 156000], ['Chair_Type_2', 135000], ['Chair_Type_2', 202500], ['Chair_Type_2', 175500], ['Chair_Type_2', 150000], ['Chair_Type_2', 225000], ['Chair_Type_2', 195000], 

['Chair_Type_3', 100000], ['Chair_Type_3', 150000], ['Chair_Type_3', 130000], ['Chair_Type_3', 120000], ['Chair_Type_3', 180000], ['Chair_Type_3', 156000], ['Chair_Type_3', 135000], ['Chair_Type_3', 202500], ['Chair_Type_3', 175500], ['Chair_Type_3', 150000], ['Chair_Type_3', 225000], ['Chair_Type_3', 195000], 

['Chair_Type_4', 100000], ['Chair_Type_4', 150000], ['Chair_Type_4', 130000], ['Chair_Type_4', 120000], ['Chair_Type_4', 180000], ['Chair_Type_4', 156000], ['Chair_Type_4', 135000], ['Chair_Type_4', 202500], ['Chair_Type_4', 175500], ['Chair_Type_4', 150000], ['Chair_Type_4', 225000], ['Chair_Type_4', 195000]]

Comments


bottom of page