Another Python cheat sheet
Tags: python
Published: 2021-11-29 10:23:12

Basics 
---------------------------------------------

### Types

*   **string**
*   **int, float**
*   **lists**:

```python
names = ["Scarlett Johansson", "Anne Hathaway", "Jessica Alba"]
```
    
*   **tuples**: immutable collections of elements separated by commas and enclosed in parentheses

```python   
tup = ('Checkers', 1945, 'Washington')
print(tup)
```
    
*   **sets**: mutable collections of objects separated by commas and enclosed in curly brackets or the set function

```python
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
    
```python
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

```python
names = ["Scarlett", "Anne", "Jessica"] 
    
for actress in actresses:
    print(actress)
```

### Loops 

[follow my guide on Python loops](https://dev.to/jmau111/bad-loop-good-loop-in-python-ahf) 

### List comprehensions 

It's a convenient, compact and more readable syntax for lists and loops:

```python
numbers = [n for n in range(112) if n%3 == 0]
print(numbers)
```

There are comprehensions for sets and dictionaries too. 

### Generators 

[Follow my guide on generators](https://dev.to/jmau111/make-sense-of-generators-doa) 

### Pro tips 

[Follow my guide on pro tips](https://dev.to/jmau111/python-pro-tips-27cb) 

### Errors and exceptions 

Read [the documentation about exceptions](https://docs.python.org/3/library/exceptions.html). 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](https://docs.python.org/3/tutorial/modules.html)

### Imports 

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

[Follow my guide on Python imports](https://dev.to/jmau111/about-python-imports-19i1) 

### itertools 

An essential module you have to know is [the itertools module](https://docs.python.org/3/library/itertools.html). 

It allows you to handle lists and dictionaries in a very efficient way, optimizing the memory usage. 

### OS module 

[The OS module](https://docs.python.org/3/library/os.html) is useful to handle directories, files and paths.

Pip 
------------------------------------

pip is [the package installer for Python](https://pypi.org/). You can use it to download any package or module.

Python for the web 
---------------------------------------------------------------------------------

### Django 

[Django](https://docs.djangoproject.com/en/) is a secure and scalable framework to build websites with Python. It has everything you need for web development. 

### Flask 

[Flask](https://flask.palletsprojects.com/en/2.0.x/) is more minimalistic and lighter than Django, but it has way less features and functionalities. I would not recommend it for beginners. 

### Pyramid 

[Pyramid](https://trypyramid.com/documentation.html) 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

```python
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](https://github.com/python/cpython/blob/main/Lib/re.py) 

### 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.

```python
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.

```python
def make_lambda(n):
    return lambda a: a + n
```

### Execute code only if run directly, not when imported

```python
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](https://code.visualstudio.com/) via the terminal. In addition, you'll get helpful and free VS code extensions to speed up your dev. 

### Pycharm 

[Pycharm](https://www.jetbrains.com/pycharm/) is one the best IDE for professional use of Python. You won't probably need any other software. 

### Jupyter 

[Jupyter](https://jupyter.org/) supports interactive data science and scientific computing across all programming languages including Python.