Another Python cheat sheet

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 and num2 = 7 point to the same memory slot
  • likewise, values such as none or true (or false) 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

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.

Imports

You can import built-in modules, third-party libraries and even your own modules.

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

Pip

pip is the package installer for Python. You can use it to download any package or module.

Python for the web

Django

Flask

Pyramid

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

Jupyter

16