# Discovering Six Lesser-Known Python Features
Written on
Chapter 1 Uncovering Hidden Gems in Python
Having been involved in Python programming since 2017, I recently discovered six features that I was unaware of until last year.
Section 1.1 Enhanced Printing with 'pprint'
When dealing with complex data structures, such as a deeply nested dictionary, printing can be cumbersome. For example, consider the following copyshop data:
copyshops = {
"A": {
"apple": {"price": 1, "quantity": 100},
"orange": {"price": 2, "quantity": 200},
"pear": {"price": 3, "quantity": 300},
},
"B": {
"apple": {"price": 4, "quantity": 400},
"orange": {"price": 5, "quantity": 500},
"pear": {"price": 6, "quantity": 600},
},
"C": {
"apple": {"price": 7, "quantity": 700},
"orange": {"price": 8, "quantity": 800},
"pear": {"price": 9, "quantity": 900},
}
}
Instead of employing a nested loop to print this structure, we can utilize the pprint module for a more organized output:
from pprint import pprint
pprint(copyshops)
Additionally, we can customize the indentation level when using pprint:
pprint(copyshops, indent=4)
Section 1.2 Understanding Frozensets
A frozenset in Python is a type of set that cannot be altered after its creation. It operates like a regular set but is immutable. For example:
fs = frozenset([1, 2, 3])
print(fs)
Disadvantages of Frozensets:
- You cannot add or remove elements once created.
- The variable can only be reassigned to a new frozenset.
Advantages of Frozensets:
- Their immutability allows them to be used as dictionary keys.
- They can be included in other sets.
- Membership checking still operates in O(1) time.
- Methods such as .union and .intersection can still be applied.
Section 1.3 The Walrus Operator
Introduced in Python 3.8, the walrus operator := allows for variable assignment and usage within a single expression. For example, consider the following code:
score = 75
if score > 50:
print("You pass")
This can be condensed using the walrus operator:
if score := 75 > 50:
print("You pass")
Here, score := 75 assigns the value 75 to score and also returns 75, allowing for a more concise approach.
Section 1.4 String Alignment Methods
Python provides three handy methods for string alignment: .ljust, .rjust, and .center. Here’s how they work:
print("|" + "hello".ljust(20) + "|")
print("|" + "hello".rjust(20) + "|")
print("|" + "hello".center(20) + "|")
- .ljust(20) pads the string on the right to a length of 20.
- .rjust(20) pads it on the left.
- .center(20) pads it equally on both sides.
If the original string exceeds the specified length, it will remain unchanged.
Section 1.5 Serializing Multiple Objects with Pickle
While I was aware of the pickle library for serializing data, I recently learned that we can pickle multiple objects in a loop. Here’s a quick example:
fruits = ["apple", "orange", "pear"]
prices = [4, 5, 6]
quantities = [100, 200, 300]
import pickle
with open("test.pckl", "wb") as f:
pickle.dump(fruits, f)
pickle.dump(prices, f)
pickle.dump(quantities, f)
This creates a test.pckl file containing the serialized lists. To deserialize them, we can do the following:
with open("test.pckl", "rb") as f:
fruits = pickle.load(f)
prices = pickle.load(f)
quantities = pickle.load(f)
print(fruits)
print(prices)
print(quantities)
Note: Ensure that the order of serialization matches the order of deserialization.
Section 1.6 Adding Color to Output
To print colored output in Python, you can use the colorama library, which you’ll need to install first:
from colorama import Fore
print(Fore.RED + "hello")
print(Fore.BLUE + "hello")
print(Fore.GREEN + "hello")
Alternatively, you can use ANSI escape codes:
print("x1b[31mhello")
print("x1b[34mhello")
print("x1b[32mhello")
However, using colorama is generally easier and more manageable.
Conclusion
I hope you discovered at least one new Python feature today!
Final Thoughts
If you're interested in further learning, consider signing up through my link to gain access to unlimited Medium articles. I create coding articles primarily focused on Python, aimed at helping others enhance their programming skills. Join my email list for updates on new publications. More content can be found at PlainEnglish.io. Don't forget to follow me on Twitter, LinkedIn, and Discord for more insights!