Another Python cheat sheet
spO0q
Posted on November 29, 2021
Basics
Types
- string
- int, float
- lists:
names = ["Scarlett Johansson", "Anne Hathaway", "Jessica Alba"]
- tuples: immutable collections of elements separated by commas and enclosed in parentheses
tup = ('Checkers', 1945, 'Washington')
print(tup)
- sets: mutable collections of objects separated by commas and enclosed in curly brackets or the set function
my_set = set(['Checkers', 1945, 'Washington'])
print(my_set)
- dictionaries: unordered collections that contain key:value pairs separated by commas and enclosed in curly brackets
movies = {"Actresses": ["Scarlett Johansson", "Anne Hathaway", "Jessica Alba"], "Directors": ["Sofia Coppola", "Nacho Vigalondo", "James Cameron"]}
Assignments and memory
Each Python object can have a name. Python has internal optimizations, for example with integers:
- it uses the same memory slot for integers less than 256
-
num = 7
andnum2 = 7
point to the same memory slot - likewise, values such as
none
ortrue
(orfalse
) point to the same object in memory
Multiple assignments in one line
num,num2 = 7,2
. While it's possible, don't overuse it. It's less readable.
Lists
names = ["Scarlett", "Anne", "Jessica"]
for actress in actresses:
print(actress)
Loops
follow my guide on Python loops
List comprehensions
It's a convenient, compact and more readable syntax for lists and loops:
numbers = [n for n in range(112) if n%3 == 0]
print(numbers)
There are comprehensions for sets and dictionaries too.
Generators
Pro tips
Errors and exceptions
Read the documentation about exceptions. You must know them.
Modules
Getting started
Python modules are files containing reusable functions, like a toolbox. It's relatively easy to import any module with the keyword import
in other python files, making the code more modular and easier to maintain.
Read the documentation about modules
Imports
You can import built-in modules, third-party libraries and even your own modules.
Follow my guide on Python imports
itertools
An essential module you have to know is the itertools module.
It allows you to handle lists and dictionaries in a very efficient way, optimizing the memory usage.
OS module
The OS module is useful to handle directories, files and paths.
Pip
pip is the package installer for Python. You can use it to download any package or module.
Python for the web
Django
Django is a secure and scalable framework to build websites with Python. It has everything you need for web development.
Flask
Flask is more minimalistic and lighter than Django, but it has way less features and functionalities. I would not recommend it for beginners.
Pyramid
Pyramid is a nice alternative approach. It's more like Flask than Django, but they do handle views in a very Django way.
Advanced concepts
Handle JSON
import json
data = {
"fire": "starter"
}
with open("myfile.json", "w") as dest:
json.dump(data, dest, indent="\t")
The above code write JSON data in myfile.json
. Regular expressions Import the re package
Args and kwargs
Python has the splat operator (*) which is universally used as the multiply operator in math, but Python adds extra functionalities if it's used in front of a variable.
def straight_forward(func, *args, **kwargs):
return func(*args, **kwargs)
With the above function, I can forward any function regardless of the parameters.
Lambda Functions
Lambda functions are anonymous functions that evaluate expressions only.
def make_lambda(n):
return lambda a: a + n
Execute code only if run directly, not when imported
if __name__ == "__main__":
# code
Machine learning
Python is a great choice if you want to learn machine learning, data science and other trendy topics:
Data is the new Oil
And Python might help you to build your own drilling rig.
Editors and softwares
VS code
When Python is correctly installed on your machine, you can execute Python with Visual Studio code via the terminal. In addition, you'll get helpful and free VS code extensions to speed up your dev.
Pycharm
Pycharm is one the best IDE for professional use of Python. You won't probably need any other software.
Jupyter
Jupyter supports interactive data science and scientific computing across all programming languages including Python.
Posted on November 29, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.