Python
Homepage / Notes / Computer Science / Programming Languages / Python
Language Features
Strings
'hello'hello
Numbers
1 + 12
Ranges
for i in range(1, 5):
print(i)1
2
3
4
List Comprehensions
[x**2 for x in range(5)][0, 1, 4, 9, 16]
[x for x in range(10) if x % 2 == 0][0, 2, 4, 6, 8]
Classes
Docs: https://docs.python.org/3/tutorial/classes.html
Most basic example:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'About __init()__:
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)Conventions
Single leading underscore: var
Hint to the programmer that it is for internal use only. Not enforced in any way.
Double leading underscore: _var
"Name mangling".
>>> class Test:
... def __mangled_name(self):
... pass
... def normal_name(self):
... pass
...
>>> t = Test()
>>> [attr for attr in dir(t) if "name" in attr]
['_Test__mangled_name', 'normal_name']Single trailing underscore: var_
To avoid naming conflicts, for example class_.
Double leading and trailing underscore: var
Reserved for spcial use like __init__.
Single underscore: _
By convention, used as a temporary variable name.
Type hints
Typing
Docs: https://docs.python.org/3/library/typing.html
Not enforced in any way, only there to help.
Basic example
Takes a string, outputs a string:
def greeting(name: str) -> str:
return 'Hello ' + namePattern Matching
Introduced in Python 3.10
def string_age(age):
match age:
case x if x < 6:
return "User is very young"
case x if 6 <= x < 18:
return "User is a minor"
case x if 18 <= x < 65:
return "User is an adult"
case x if 65 <= x:
return "User is probably retired"
print(string_age(2))
print(string_age(12))
print(string_age(22))
print(string_age(90))User is very young
User is a minor
User is an adult
User is probably retired
itertools
repeat
from itertools import repeat
return list(repeat('A', 3))| A | A | A |
combinations
from itertools import combinations
return list(combinations('ABC', 2))| A | B |
| A | C |
| B | C |
permutations
from itertools import permutations
return list(permutations('ABC', 2))| A | B |
| A | C |
| B | A |
| B | C |
| C | A |
| C | B |
batched
from itertools import batched
return list(batched(['green', 'blue', 'red', 'yellow', 'black', 'pink'], 2))Libraries
NumPy
Scientific Computing
NumPy's main object if the multidimensional array, called ndarray. Different from standard Python array, which only handles one-dimensional arrays. Dimensions are called axes.
pip3 install numpyBasics
import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
print(a.shape)(3, 5)
print(a.ndim)2
print(a.size)15
Creating
You can create an array from a regular Python list
b = np.array([1, 2, 3, 4])
print(b)[1 2 3 4]
Or zeros / ones
print(np.zeros((3, 4)))[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
print(np.ones((2, 3, 4)))[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]
Operations
a = np.array([100, 100, 100])
b = np.array([10, 20, 30])
print(a - b)[90 80 70]
print(b*2)[20 40 60]
Pandas
pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool
pip3 install pandasBasics
Basic object of pandas is the DataFrame. A DataFrame is made of rows and columns, like a spreadsheet. Each column in a DataFrame is a Series.
import pandas as pd
df = pd.DataFrame(
{
"Name": [
"Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",
],
"Age": [22, 35, 58],
"Sex": ["male", "male", "female"],
}
)
print(df) Name Age Sex
0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
Series
Selecting a single Series
print(df["Age"])0 22
1 35
2 58
Name: Age, dtype: int64
print(df["Age"].max())58
print(df["Age"].describe())count 3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000
50% 35.000000
75% 46.500000
max 58.000000
Name: Age, dtype: float64
IceCream
https://github.com/gruns/icecream
Never use print() to debug again.
Arrow
https://arrow.readthedocs.io/en/latest/
Better dates & times for Python
Rich
https://github.com/willmcgugan/rich
Rich is a Python library for rich text and beautiful formatting in the terminal.
Kats
https://facebookresearch.github.io/Kats/
One stop shop for time series analysis in Python
Darts
https://github.com/unit8co/darts
A Python library for easy manipulation and forecasting of time series.
Numba
Numba makes Python code fast
Numba is an open source JIT compiler that translates a subset of Python and NumPy code into fast machine code.
Pyscript
https://github.com/pyscript/pyscript
PyScript is a Pythonic alternative to Scratch, JSFiddle, and other "easy to use" programming frameworks, with the goal of making the web a friendly, hackable place where anyone can author interesting and interactive applications.
Textual
https://textual.textualize.io/
Textual is a framework for building applications that run within your terminal. Text User Interfaces (TUIs) have a number of advantages over web and desktop apps.
Ibis
An open source dataframe library that works with any data system
Resources
https://learnpythontherightway.com/
https://python-poetry.org/
Layman's Guide to Python Built-in Functions
https://www.mattlayman.com/blog/2024/layman-guide-python-built-in-functions/
Python Tricks: A Buffet of Awesome Python Features
by Dan Bader