22 Things I Never Knew About Python Until Recently (Compilation)
# Despite working with Python since 2017

1) Infinity values in Python
a = float("inf")
b = float("-inf")We can define infinity values in Python (above). Positive infinity is larger than all numbers, while negative infinity is smaller than all numbers.
2) Using ‘pprint’ to print stuff nicely
We can use pprint to nicely print out complicated data structures without having to write any loops.
from pprint import pprintd = {"A":{"apple":1, "orange":2, "pear":3}, "B":{"apple":4, "orange":5, "pear":6}, "C":{"apple":7, "orange":8, "pear":9}}pprint(d)
3) Printing coloured output using ‘colorama’
from colorama import Foreprint(Fore.RED + "hello world")
print(Fore.BLUE + "hello world")
print(Fore.GREEN + "hello world")
4) A less annoying way to create dictionaries
d1 = {"apple":"pie", "orange":"juice", "pear":"cake"}
d2 = dict(apple="pie", orange="juice", pear="cake")Here, d1 and d2 contain the exact same key-value pairs. For d2, we use dict() to create the dictionary so we don’t have to deal with too many inverted commas.
5) Unprinting stuff in Python
CURSOR_UP = "\033[1A"
CLEAR = "\x1b[2K"The "\033[1A" escape character moves our cursor up by 1 line, and the "\x1b[2K" character clears the entire current line. If we print them together, we can essentially ‘unprint’ an entire line in our terminal
print("apple")
print("orange")
print("pear")print((CURSOR_UP + CLEAR)*2, end="") # UNPRINTS 2 LINES
print("pineapple")
Note — remember to use the end="" option in the print function.
6) Private variables in classes are not really private
class Dog:
def __init__(self, name):
self.__name = name # Supposed private variable @property
def name(self):
return self.__nameHere the __name attribute in the Dog class is supposed to be a private attribute (we shouldn’t be able to access it directly). But except it’s not really private.
dog = Dog("fifi")
print(dog.__dict__) # {'_Dog__name': 'fifi'}We can use the __dict__ attribute to access it directly (and even change it)!
7) We can use type() to create classes without using ‘class’ keyword
classname = type(name, bases, dict)nameis the name of the classbasesis a tuple that contains other classes that this inherits fromdictis a dictionary containing its attributes and methods
Normal way of creating a class:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("woof")Creating the same class using type():
def init(self, name):
self.name = namedef bark(self):
print("woof")Dog = type("Dog", (), {"__init__":init, "bark":bark})8) We can use Chinese characters as variable names
我 = 4
你 = 5print(我 + 你) # 9We can use emojis too, or nearly any unicode character. Cool and interesting fact, but don’t use this in production.
9) Python has a backspace character
print("abc" + "\b" + "d")# abdThe backspace character \b backspaces the stuff that we print.
10) Making a bell sound with Python
print("\a")The \a is the bell character, and printing it makes a bell sound. (Try it in terminal/cmd)
11) We can use classes as decorators
This is possible due the the __call__ magic method.
class add():
def __init__(self, char):
self.char = char def __call__(self, function):
def inner(*args):
return function(*args) + self.char
return inner@add("!")
def greet(name):
return "hello " + nameprint(greet("jerry"))# hello jerry!Here, the add decorator takes in a character, and simply adds this character to the back of whatever the function returns.
12) Functions can have variables
def hello():
hello.hi = "hi world"
return "hello world"print(hello()) # hello world
print(hello.hi) # hi worldNot the most useful feature, but it’s interesting!
13) Aligning strings using ljust, rjust, center
The methods .ljust, .rjust and .center allow us to align our strings and pad them using whitespace characters.
print(">" + "hello".ljust(20) + "<")
print(">" + "hello".rjust(20) + "<")
print(">" + "hello".center(20) + "<")
The formatted string (f-string) version:
hello = "hello"
print(f">{hello:<20}<")
print(f">{hello:>20}<")
print(f">{hello:^20}<")
14) I added a list to itself and got this
lis = [1, 2]
lis.append(lis)
print(lis)# [1, 2, [...]]The ... here is known as an ellipsis in Python, and can be used in place of the pass keyword, which tells Python to do absolutely nothing.
15) we can use eval() to run Python code in strings
x = eval("1+2*3-4")# x is 3Here, the built-in eval() function can be used to execute Python code inside strings. Another example:
n = 4
x = eval("n + 10")# x is 1416) The round() function accepts negative decimal places
We probably knew early on the the round function can be used to round numbers to a certain number of decimal places. But did you know that we can also use it to round off to the nearest 10, 100, 1000 and so on?
x = 12345
print(round(x, -1)) # 12340
print(round(x, -2)) # 12300
print(round(x, -3)) # 12000
print(round(x, -4)) # 10000
print(round(x, -5)) # 0I should probably have known this much earlier, but somehow didn’t so yeah
17) The walrus operator
The walrus operator := was introduced in Python 3.8. It’s basically the same as the assignment operator =, but it also returns the value itself. We can thus save one line of code when writing conditional statements.
x = 5
if x > 3:
print("x is more than 3")This is the same as:
if (x := 5) > 3:
print("x is more than 3")18) We can pickle multiple objects into the same file
The built-in pickle library allows us to save (serialize) Python data structures into pickle files. Pickling (saving) multiple objects:
a = ["apple", "orange", "pear"]
b = ["pineapple", "banana", "durian"]
c = ["grape", "jackfruit", "mango"]import picklewith open("test.pckl", "wb") as f:
pickle.dump(a, f) # saving a into test.pckl
pickle.dump(b, f) # saving b into test.pckl
pickle.dump(c, f) # saving c into test.pcklUnpickling (reading) them from the pickle file:
import picklewith open("test.pckl", "rb") as f:
a = pickle.load(f)
b = pickle.load(f)
c = pickle.load(f)print(a)
print(b)
print(c)
19) The -O flag allows us to ignore assert statements
# run.pyassert 1==2
print("hello")If we run this code above normally, we get an AssertionError, as 1==2 evaluates to a False. However, we can bypass the assert statement if we use the -O flag when running our Python script.
python3 -O run.py# helloAdding the -O flag tells Python to ignore any assert statements!
20) Creating dictionaries easily using dict.fromkeys
If we wish to create a dictionary with default values quickly, we can consider using the dict.fromkeys method instead of a comprehension.
fruits = ["apple", "orange", "pear"]d = dict.fromkeys(fruits)# d is {'apple': None, 'orange': None, 'pear': None}We can modify the default value by passing in another argument. Here, we pass in an empty list [] as the second argument to dict.fromkeys, so all values in the new dictionary will be [].
fruits = ["apple", "orange", "pear"]d = dict.fromkeys(fruits, [])# d is {'apple': [], 'orange': [], 'pear': []}21) Frozensets in Python
A frozenset is a built-in data structure in Python — it is essentially an immutable set. This means that we cannot change it in any way AFTER we’ve created it.
fs = frozenset({1, 2, 3})Cons of using frozensets:
- We cannot change it after we create it (immutability) — we cannot add or remove anything from a frozenset.
Pros of using frozensets:
- We can use frozensets as dictionary keys
- We can add frozensets as values into another set.
- Checking if a frozenset contains a value still takes constant O(1) time.
22) We can force a classes to accept only certain attributes using __slots__
class Dog:
__slots__ = ["name", "age"]dog = Dog()
dog.name = "fifi" # no problem
dog.age = 5 # no problem
dog.breed = "german shepherd" # ERRORHere in the Dog class, we define __slots__ to only take in name and age. Our Dog class can thus only accept name and age attributes! If we try to assign something else eg. breed to our Dog object, we get an error.
Conclusion
Hopefully you learnt at least one new thing about Python after reading this!
Some Final words
If this article provided value and you wish to support me, do consider signing up for a Medium membership — It’s $5 a month, and you get unlimited access to articles on Medium. If you sign up using my link below, I’ll earn a tiny commission at zero additional cost to you.
Sign up using my link here to read unlimited Medium articles.
Get my free Ebooks: https://zlliu.co/books
I write programming articles (mainly Python) that would have probably helped the younger me a lot. Do join my email list to get notified whenever I publish.
More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
