#11 - Python Comprehensions

#11 - Python Comprehensions

By Ifeanyi Omeata


Topics:


1. List Comprehensions
2. List Comprehensions with Conditions
3. List Comprehensions with Complex Conditions
4. List Comprehensions with Walrus Operator
5. Set Comprehensions
6. Dictionary Comprehensions
7. Nested Dictionary Comprehensions
8. Using map() Objects
9. Using filter() Objects


1. List Comprehensions


>>Return to Menu
Syntax:

(values) = [ (expression) for (value) in (collection) ]

For Example:

# squares_2 = []
# for x in range(10):
#     squares_2.append(x*x)
# print(squares_2)

squares = [x*x for x in range(10)]
print(squares)

image.png


2. List Comprehensions with Conditions


>>Return to Menu
Syntax:

(values) = [ (expression) for (value) in (collection) (if condition) ]

For Example:

# squares_2 = []
# for x in range(10):
#     if x % 2 == 0:
#         squares_2.append(x*x)
# print(squares_2)

even_squares = [x*x for x in range(10) if x % 2 == 0]
print(even_squares)

image.png


3. List Comprehensions with Complex Conditions


>>Return to Menu

sentence = 'The rocket, who was named Ted, came back from Mars because he missed his friends.'

def is_consonant(letter):
    vowels = 'aeiou'
    return letter.isalpha() and letter.lower() not in vowels

consonants = [i for i in sentence if is_consonant(i)]
print(consonants)

Same as:

vowels = [i for i in sentence if i in 'aeiou']

image.png


4. List Comprehensions with Walrus Operator


>>Return to Menu
The walrus operator solves the problem of running a conditional expression while simultaneously assigning the output value to a variable.

import random

def get_weather_data():
    return random.randrange(90, 110)

hot_temps = [temp for _ in range(20) if (temp := get_weather_data()) >= 100]

print(hot_temps)

image.png


5. Set Comprehensions


>>Return to Menu
A set comprehension is almost exactly the same as a list comprehension in Python. The difference is that set comprehensions make sure the output contains no duplicates. You can create a set comprehension by using curly braces instead of brackets.

quote = "life, uh, finds a way"
unique_vowels = {i for i in quote if i in 'aeiou'}

print(unique_vowels)

image.png


6. Dictionary Comprehensions


>>Return to Menu
Dictionary comprehensions are similar to List comprehensions, with the additional requirement of defining a key and curly braces.

squares = {i: i * i for i in range(10)}

print(squares)

image.png

For Loop:

dict_squares = {}
for i in range(5):
    dict_squares[i] = i*i

print(dict_squares)

Will be expressed in dict_comp as:

#dict_1 = {key:value for (key,value) in iterable}

dict_1 = {i:i*i for i in range(5)}
print(dict_1)

#dict_2 = {key:value for (key,value) in iterable (condition)}
dict_1 = {i:i*i for i in range(5) if i%2 == 0}
print(dict_1)

#dict_2 = {key:value for (key,value) in iterable (condition)}
dict_1 = {i:i*i for i in range(5) if i%2 == 0 if i != 0}
print(dict_1)

image.png

Others:

sentence = "I am Adenike and I am a Software Engineer"
words = sentence.split()
set_comp = {word for word in words if len(word) > 3}
print(set_comp)


7. Nested Dictionary Comprehensions


>>Return to Menu

a = [1,2]
b = [3,5]

nested_dict_sum = {f"sum{(a[i],b[j])}": a[i]+b[j] for i in range(len(a)) for j in range(len(b))}
print(nested_dict_sum)
print(type(nested_dict_sum))

nested_dict = {(i,j): i+j for i in range(2) for j in range(2)}
print(nested_dict)

image.png


8. Using map() Objects


>>Return to Menu

map(function, iterable)

map() provides an alternative approach that’s based in functional programming. You pass in a function and an iterable, and map() will create an object. This object contains the output you would get from running each iterable element through the supplied function.

trxns = [1.09, 23.56, 57.84, 4.56, 6.78]
TAX_RATE = .08

def get_price_with_tax(trxn):
    return round(trxn * (1 + TAX_RATE), 2)

final_prices = map(get_price_with_tax, trxns)

print(list(final_prices))

image.png


9. Using filter() Objects


>>Return to Menu

filter(function, iterable)

This function plays the role of a decision function, also known as a filtering function, because it provides the criteria to filter out unwanted values from the input iterable and to keep those values that you want in the resulting iterable. Note that the term unwanted values refers to those values that evaluate to false when filter() processes them using function. An important point regarding filter() is that it accepts only one iterable.

numbers = [-2, -1, 0, 1, 2]

def is_positive(n):
    return n > 0

extract_positive = filter(is_positive, numbers)

print(extract_positive)
print(list(extract_positive))

image.png

#End


Hope you enjoyed this! :) Follow me for more contents...


Get in Touch:
ifeanyiomeata.com

Youtube: youtube.com/c/IfeanyiOmeata
Linkedin: linkedin.com/in/omeatai
Twitter: twitter.com/iomeata
Github: github.com/omeatai
Stackoverflow: stackoverflow.com/users/2689166/omeatai
Hashnode: hashnode.com/@omeatai
Medium: medium.com/@omeatai
© 2022