Python Fundamentals


List Comprehension


General syntax for creating list comprehension: for each item in the iterable, we evaluate the expression on the left - the result of the evaluation becomes the element of the list.

#General Syntax for List Comprehensions
[expression(item) for item in iterable]

#Example
s = "Hello World"
l = [ len(s) for word in s] #[5,5]

Dictionary Comprehension


Here, for each item in the iterable, we evaluate the key and the value.

# Syntax for Dictionary Comptehension
{
key_expression(item): value_expression(item)
for item in iterable
}

# Example 1
squares_dict = {num:num*num for num in range(1,11)}

# Example 2
old_price: {'milk':1.02,'coffee':2.5, 'bread':2.5}
multiplier = 0.76
new_price: { key: value*multiplier  for (key,value) in old_price.items()}

Dictionary comprehensions do NOT work directly on dict sources, instead use dict.items()

Filtering Comprehensions