Python has a number of advantages over other programming languages, but the hallmark advantage is its readability. Python is considered to be one of the most readable programming languages. It is often compared to other languages such as Java, C++, and Perl. Python is said to be more readable because it uses English keywords instead of punctuation. It also has a consistent indentation style, and a simple data structure.
Other languages use curly braces to define code blocks, which can make the code more difficult to read. Python’s use of white space makes it more readable and easier to understand. However, it is possible to design even more elegant code even while using the Python programming language.
There’s no doubt that Python is a fantastic language, with powerful constructs and features to help create elegant, efficient code.
List comprehension, dictionary comprehension, and generator expressions are three powerful examples of such expressions that are very useful.
We’ll begin with a basic example of for loops, then move onto list comprehensions, dictionary comprehensions, and finally to generator expressions to show how each of these can help make your Python code more concise.
For-loop
A for-loop in Python iterates through a sequence of values and executes a block of code for each value in the sequence. The code block executed by the for-loop can access the current value from the sequence using the loop variable.
For example, the following for-loop iterates through a list of integers and prints the square of each integer in the list:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num * num)
Output
# 1
# 4
# 9
# 16
# 25
In the example above, the loop variable num takes on each value in the list numbers in turn. For each value, the loop prints the value multiplied by itself.
Range() function
The range() function in Python is used to generate sequential numbers. The function takes two parameters, a start value and an end value, and returns sequential numbers from the start value to the end value.
For example, if the start value is 0 and the end value is 5, the list returned would be [0, 1, 2, 3, 4].
If the start value is omitted, the list will start at 0.
The range() function is often used in for loops to iterate through a list of values.
For example:
for i in range(0, 5):
print(i)
Output
# 0
# 1
# 2
# 3
# 4
List comprehension
A list comprehension in Python is a way to create a list from another list or iterable. It is a shorthand way to create a list without having to write a for loop.
They are written as follows:
[expression for item in iterable]
The expression can be anything that returns a value. The item is each element in the iterable. The list comprehension will return a list of the results of the expression for each item in the iterable.
For example, if you have a list of numbers and you want to square each number, you can use list comprehensions:
numbers = [1, 2, 3, 4, 5]
squares = [number**2 for number in numbers]
This will return a list of the squares of each number in the numbers list.
List comprehensions with conditions
List comprehensions can also be used with conditions. For example, if you only want to square the numbers that are even, you can do this:
numbers = [1, 2, 3, 4, 5]
even_squares = [number**2 for number in numbers if number % 2 == 0]
This will return a list of the squares of the even numbers in the numbers list.
How to create dictionaries in Python
A dictionary in Python is a collection of key-value pairs. Each key is associated with a value, which can anything, e.g. a number, a string, a list, or even another dictionary. You can access the values in a dictionary by using the keys.
For example, the Python dictionary named “animals” contains the following key-value pairs:
animals = {
"cat": "feline",
"dog": "canine",
"bird": "avian"
}
print(animals)
Output
{'cat': 'feline', 'dog': 'canine', 'bird': 'avian'}
You can also add new key-value pairs to a dictionary. For example, you could add a new key-value pair like this:
animals["monkey"] = "primate"
This would add a new key named “monkey” with the value “primate” to the animals dictionary.
Python dictionary comprehension
A dictionary comprehension is a concise way to create a dictionary in Python. It consists of an expression followed by a for statement, then zero or more for or if statements. The result is a new dictionary with the same keys as the original, but with the values transformed by the expression.
In general, a dictionary comprehension has the following syntax:
{key: value for (key, value)}
or optionally:
{key: value for (key, value) in iterable if condition(key, value)}
Where key is the new key, value is the new value, iterable is the existing dictionary, and condition is an optional function that determines whether or not to include a particular key-value pair in the new dictionary.
Note that the order of the for and if statements in a dictionary comprehension is important. The for statement must come first, followed by the if statement. This is because the for statement creates the new dictionary, and the if statement filters the key-value pairs that are added to the new dictionary.
Here is a simple example of a dictionary comprehension:
my_dict = {'a': 1, 'b': 2, 'c': 3}
new_dict = {key: value * 2 for (key, value) in my_dict.items()}
print(new_dict)
Output
{'a': 2, 'b': 4, 'c': 6}
In this example, the dictionary comprehension takes each key-value pair from the my_dict dictionary, and creates a new key-value pair in the new_dict dictionary, with the value being double the original value.
Generator in Python
Generators are a convenient way to produce a sequence of results without having to store all the values in data structures in memory. For example, if you want to generate a sequence of numbers, you can use a generator function to produce the sequence instead of storing all the numbers in a list.
Generator functions are defined like normal functions, but they use the yield keyword to generate numbers. When a generator function is called, it returns a generator object. This object can be used to produce the sequence of results. Each time the next() method is called on the generator object, the generator resumes execution and produces the next value in the sequence.
Here is an example of a generator function that produces a sequence of numbers:
def generate_numbers(n):
for i in range(n):
yield i
This function produces a sequence of numbers from 0 to n-1. To generate the sequence, you can create a generator object like this:
generator = generate_numbers(5)
This object can be used to generate the sequence of numbers by calling the next() method:
print(next(generator))
Output
0
print(next(generator))
Output
1
print(next(generator))
Output
...
Once the end of the sequence is reached, the generator raises a StopIteration exception.
Generator expression
A generator expression is a concise way to create a new list by applying an operation to each item in an existing list. It is similar to a list comprehension, but instead of creating a list, it creates a generator object.
To create a generator expression, you put the expression inside of parentheses instead of square brackets. For example, the following list comprehension:
my_list = [1, 2, 3, 4, 5]
squares = [x*x for x in my_list]
can be rewritten as a generator expression:
my_list = [1, 2, 3, 4, 5]
squares = (x*x for x in my_list)
The only difference is that you use parentheses instead of square brackets. When you run this code, you’ll see that squares is now a generator object.
Output
<generator object <genexpr> at 0x7faacfff8580>
Business Cases for dictionary comprehensions
Dynamic Pricing Adjustments
For ecommerce, dynamic pricing may be crucial to the functioning of your business. Using dictioprices of the products you may be lacking in your stocks, while decreasing the price of the less popular ones.
For example:
# Original product prices and inventory levels
products = {
"laptop": {"price": 1000, "stock": 50},
"phone": {"price": 500, "stock": 150},
"tablet": {"price": 300, "stock": 0},
}
# Adjust prices based on stock levels
adjusted_prices = {
product: {
"price": price_data["price"] * 1.2 if price_data["stock"] < 50 else price_data["price"] * 0.9
}
for product, price_data in products.items()
}
# If stock is low (<50), price increases by 20%; if stock is high, price drops by 10%.
# Output: {'laptop': {'price': 1200.0}, 'phone': {'price': 450.0}, 'tablet': {'price': 300.0}}
Rate-limiting an API
If you have an API, it’s important to keep users from abusing it. With list and dictionary comprehension, you can easily track user requests based on their IPs and limit them as needed. Using the following code as an example, you can make a dictionary based rate limiter.
import time
# Mock request log (user: [timestamps of requests])
request_log = {
"192.168.0.1": [time.time() - 10, time.time() - 5],
"192.168.0.2": [time.time() - 50, time.time() - 45],
"192.168.0.3": [time.time() - 100, time.time() - 90],
}
# Rate limit: 3 requests per 60 seconds
max_requests = 3
time_window = 60
# Filter requests for rate-limiting (only keep requests within the time window)
valid_requests = {
user: [timestamp for timestamp in timestamps if time.time() - timestamp <= time_window]
for user, timestamps in request_log.items()
}
# Check if a user has exceeded the rate limit
rate_limit_status = {
user: "Blocked" if len(valid_requests[user]) > max_requests else "Allowed"
for user in valid_requests
}
# Output: {'192.168.0.1': 'Blocked', '192.168.0.2': 'Allowed', '192.168.0.3': 'Allowed'}
Stock Price Tracker
If you’re looking to track some stock prices, you can use the following example to create a new dictionary and a function that will track selected stock prices from an API and alert you if they cross a threshold set by you by using the following dict function.
import requests
import time
# API to fetch stock data
STOCK_API_URL = "https://api.example.com/stock"
# Threshold for stock price alert
PRICE_THRESHOLD = 1500.0
# Real-time stock prices for a list of stocks (ticker symbols)
stocks = ["AAPL", "GOOGL", "AMZN", "TSLA"]
# Function to fetch stock prices from the API
def fetch_stock_price(ticker):
response = requests.get(f"{STOCK_API_URL}/{ticker}")
return response.json()["price"]
# Monitor stocks and trigger an alert if price crosses threshold
def monitor_stocks():
alerts = {
stock: "Alert: Price crossed threshold!" if fetch_stock_price(stock) > PRICE_THRESHOLD else "Price stable"
for stock in stocks
}
return alerts
# Continuously check the stock prices in real-time
while True:
stock_alerts = monitor_stocks()
print(stock_alerts)
time.sleep(60) # Update every minute
Conclusion
Generator expression, list, and dictionary comprehension are three powerful tools that allow you to succinctly create lists and dictionaries by iterating over another list or dictionary. They are very efficient and can save you a lot of time and code.