← All writing

Python Series

A practical Python reference covering packages, virtual environments, language features and scientific computing. Includes notes on multiprocessing, command-line tools, terminal output, dependency management and logging.

Python Series

Pip

What is pip?

  • pip stands for "Pip Installs Packages" (a recursive acronym).
  • It’s the default package manager for Python.
  • You use it to install, upgrade, or remove third-party libraries (things that don’t come built into Python).
  • pip connects to the Python Package Index (PyPI), a huge repository of Python libraries.
  • It lets you easily extend Python with extra tools like NumPy (math), Flask (web apps), Pandas (data), etc.

Virtual environment

A virtual environment in Python is basically a self-contained workspace that has its own Python interpreter and its own installed libraries.

Without a virtual environment:

  • All pip install packages go into the system Python (shared by everything).
  • This can cause conflicts: e.g., Project A needs numpy==1.21, Project B needs numpy==2.0. You can’t have both installed system-wide at the same time.

With a virtual environment:

  • Each project has its own isolated dependencies.
  • No conflicts, no need for sudo, and your system Python stays clean.

Usage

Create a new virtual environment

sh
python -m venv C:\path\to\new\virtual\environment

sh
cd ~/6.5840
python3 -m venv saber

Create a virtual environment with name saber under folder ~/6.5840

Activate virtual environment

sh
source saber/bin/activate
(saber) saber@Saber:~/6.5840$

How it works

When you create a virtual environment:

  1. Python makes a folder (usually called venv/) in your project.
  2. Inside it, it copies a lightweight Python interpreter.
  3. Any pip install goes into venv/lib/... instead of system directories.

You then activate it, and your shell will use the venv’s Python + pip automatically.

Vanilla

Sort

python
# sort inplace (change origin array)
a.sort()

with as

General form:

python
with expression as variable:
    # use variable here

  • expression must return an object that supports the context manager protocol (has __enter__ and __exit__ methods).
  • as variable just assigns the result of expression.__enter__() to that variable.
  • When the block exits (even if there’s an error), expression.__exit__() is automatically called to clean things up.

Example with Files

python
with open("data.txt", "r") as f:
    data = f.read()
# file is automatically closed here

Without with, you’d have to manually f.close(). With with, Python ensures cleanup.

Type hint

  • Introduced in Python 3.5 (PEP 484).
  • They don’t enforce types at runtime (Python is still dynamically typed).
  • They’re just annotations to help humans, linters (like mypy), and tools (like IDEs) understand what type you expect.
python
def add(x: int, y: int) -> int:
    return x + y

Annotations

In Python, annotations are pieces of metadata that you attach to variables, function parameters, or return values. They don’t change how the code runs — they’re just extra information that tools (like mypy, IDEs, or libraries such as Typer, FastAPI) can use.

python
def greet(name: str, age: int) -> str:
    return f"Hello {name}, you are {age} years old."

  • name: str → annotation for parameter name.
  • age: int → annotation for parameter age.
  • -> str → annotation for the return value.

Python stores these in the function’s __annotations__ dictionary:

python
print(greet.__annotations__)
# {'name': <class 'str'>, 'age': <class 'int'>, 'return': <class 'str'>}

In Python, annotations can be literally anything you want. They’re just metadata attached to a function parameter (or return value, or variable).

python
def foo(x: "this is a string", y: 123, z: [1, 2, 3]) -> "returns nothing":
    return None

print(foo.__annotations__)
#{'x': 'this is a string', 'y': 123, 'z': [1, 2, 3], 'return': 'returns nothing'}

Import local file

If two files are in different folders, the "simple" import won't work because Python doesn't know where to look.

1. The Package Way (Best Practice)

If both folders are inside a main project folder (e.g., cs336-A1), you should use absolute imports from the project root.

Code
project_root/
│
├── utils/
│   └── loggerConfig.py
└── tokenizer/
    └── BPETokenizer.py

python
from utils import loggerConfig

loggerConfig.logger.debug("Import successful!")

2.The sys.path Hack (The "Quick Fix")

python
import sys
import os

# Add the directory containing loggerConfig.py to the search path
sys.path.append(os.path.abspath("../utils")) 

import loggerConfig

Install

Python is an interpreted language, so normally you run scripts with python file.py.

But if you want a standalone executable (so you can run it like ./myapp or myapp.exe without requiring Python installed), you need a packager.

PyInstaller (most popular)

Code
pip install pyinstaller

Then run:

Code
pyinstaller --onefile your_script.py

  • Creates a dist/your_script (Linux/Mac) or dist/your_script.exe (Windows).
  • --onefile makes a single executable.
  • Without --onefile, it creates a folder with dependencies.

👉 Example:

Code
./dist/your_script

NmuPy

Note:

python
# shallow copy
originArray = np.array([1, 2, 3])
copiedArray = originArray
copiedArray[1] = 0
# now originArray[1] == 0

# function passing parameter is also shallow copy
# slice is also shallow copy

Create array

python
x = np.array([1, 2, 3, 4])
one = np.ones((2, 2))
zero = np.zero((2, 2))
normal = np.random.randn(2, 2) # 2 by 2 mean value 0, standard deviation 1

Index

python
# 创建一个数组
arr = np.array([10, 20, 30, 40, 50])

# 创建一个布尔数组
bool_idx = np.array([True, False, True, False, True])

# 使用布尔数组进行索引
filtered_arr = arr[bool_idx]

print(filtered_arr)  # 输出: [10 30 50]

# create array [0,1, ....,n]
permutation = np.arange(n);

Transposition

python
x.T

Concatenate

python
x = [1, 2, 3]
y = [4, 5, 6]
z = np.concatenate([x, y], axis = 0) # 2 by 3
z = np.concatenate([x, y], axis = 1) # 1 by 6

Operators on array

python
x = np.ones(3) + 1 # result is [2, 2, 2]
y = np.ones(3) * 5 # result is [5, 5, 5]

Rondom

python
p = [0, 1, 2, 3, 4]
np.random.shuffle(p) # p will be changed

#now p is a random shuffled permutation

b = a[p] # b = [ a[p[0]], a[p[1]], a[p[2]], a[p[3]], a[p[4]] ] 

# random number
x = np.random.randint(1,100,20) #generate 10 integer with range 1 to 100

Shape and size

python
x = np.ones((3, 4))
print(np.size) #12
print(np.shape) #(3, 4)

Linsapce

python
# create a array contains 100 points from -10 to 10 with equal distance.
xAxis = np.linspace(-10, 10, 100)

Sort

python
a = np.array[2, 3, 3, 1]
res =  np.sort(a)

sortIndex = np.argsort(a)
sortedarray = a[sortIndex]

Matplotlib

It can parse LaTex "This is $LaTex$"

Basic line plot

python
# y = x ** 2
# connected by straight line (default)
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# create a line
plt.plot(x, y, color='green', linestyle='--', linewidth=2)


plt.title("saber")

#set x,y axis name
plt.xlabel("X axis")
plt.ylabel("Y axis")

plt.show()

Scatter plot

python
# x,y:coordinate c:color, s:size/scale 
plt.scatter(x, y, c=None, s=None, marker=None, label=None)

Bar plot

python
labels = ['A', 'B', 'C', 'D']
values = [1, 10, 100, 1000]
plt.bar(labels, values)

Grid

python
plt.grid(true)

More lines

python
# y1 = x ** 2
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]

# y2 = 2x
y2 = [2, 4, 6, 8, 10]


# create y1, and give it a name by label
plt.plot(x, y1, label = "y1")

#create y2, and give it a name by label
plt.plot(x, y2, label = "y2")

plt.title("saber")

#set x,y axis name
plt.xlabel("X axis")
plt.ylabel("Y axis")

# 添加图例,loc set location
plt.legend(loc='upper left')

Hide border

python
# 获取当前坐标轴
ax = plt.gca()
# 设置坐标轴的边框(spines)
ax.spines['top'].set_visible(False)   # 隐藏上方边框
ax.spines['right'].set_visible(False) # 隐藏右方边框

Time

python
import time

# sleep 1 second
time.sleep(1)

# get current time
start = time.time()
# ... work
end = time.time()

# unit is second.
print(end-start)

Multiprocessing

python
import multiprocessing as mp


def compute_square(numbers, queue):
    """Compute the square of each number in the list."""

    print(f"Process ID: {mp.current_process().pid} is computing squares.")
    print(f"results: {[n * n for n in numbers]}")


    # Note:
    # cannot directly get return values from the function, 
    # because each process runs in its own memory space.
    # return [n * n for n in numbers]

    # Instead, we can use a queue to send results back to the main process.
    queue.put([n * n for n in numbers])

# main entry point
if __name__ == "__main__":

    q = mp.Queue()

    # create two processes
    # target is the function to run in the process
    # args is a tuple of arguments to pass to the function

    p1 = mp.Process(target=compute_square, args=([1, 2, 3, 4], q))
    p2 = mp.Process(target=compute_square, args=([5, 6, 7, 8], q))

    # start the processes
    p1.start()
    p2.start()

    # wait for the processes to finish
    p1.join()
    p2.join()

    # Get the result from the processes
    # Note: the order of results is not guaranteed
    print(q.get())
    print(q.get())
    
    print("Processes have finished execution.")

pool

python
from multiprocessing import Pool, TimeoutError
import time
import os

def f(x):
    return x*x

if __name__ == '__main__':
    # start 4 worker processes
    with Pool(processes=4) as pool:

        # print "[0, 1, 4,..., 81]"
        # pool.map is similar like map in functional programming
        # Apply f to every element in second argument which is a list
        # and produce a new list.
        # Since there are 4 workers, it will run parallel.
        print(pool.map(f, range(10)))

        # print same numbers in arbitrary order
        for i in pool.imap_unordered(f, range(10)):
            print(i)

        # evaluate "f(20)" asynchronously
        res = pool.apply_async(f, (20,))      # runs in *only* one process
        print(res.get(timeout=1))             # prints "400"

        # evaluate "os.getpid()" asynchronously
        res = pool.apply_async(os.getpid, ()) # runs in *only* one process
        print(res.get(timeout=1))             # prints the PID of that process

        # launching multiple evaluations asynchronously *may* use more processes
        multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
        print([res.get(timeout=1) for res in multiple_results])

        # make a single worker sleep for 10 seconds
        res = pool.apply_async(time.sleep, (10,))
        try:
            print(res.get(timeout=1))
        except TimeoutError:
            print("We lacked patience and got a multiprocessing.TimeoutError")

        print("For the moment, the pool remains available for more work")

    # exiting the 'with'-block has stopped the pool
    print("Now the pool is closed and no longer available")

Typer

See https://typer.tiangolo.com/tutorial for full details

First steps

A CLI option doesn't depend on the order because it has a predefined name.

So, the main and most important difference is that:

  • CLI options start with -- and don't depend on the order
  • CLI arguments depend on the sequence order

So, by default:

  • A CLI argument is required
  • A CLI option is optional

Example

python
import typer

#         argument,     argument       
def main(name: str, lastname: str, formal: bool = False):
    if formal:
        print(f"Good day Ms. {name} {lastname}.")
    else:
        print(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

sh
💬 Get the help
python main.py --help

 Usage: main.py [OPTIONS] NAME LASTNAME                            
                                                                   
╭─ Arguments ─────────────────────────────────────────────────────╮
│ *    name          TEXT  [default: None] [required]             │
│ *    lastname      TEXT  [default: None] [required]             │
╰─────────────────────────────────────────────────────────────────╯
╭─ Options ───────────────────────────────────────────────────────╮
│ --formal                --no-formal      [default: no-formal]   │
│ --help                                   Show this message and  │
│                                          exit.                  │
╰─────────────────────────────────────────────────────────────────╯

We can create option by giving a default value.

Document your CLI app

python
import typer


def main(name: str, lastname: str = "", formal: bool = False):
    """
    Say hi to NAME, optionally with a --lastname.

    If --formal is used, say hi very formally.
    """
    if formal:
        print(f"Good day Ms. {name} {lastname}.")
    else:
        print(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

sh
python main.py --help

 Usage: main.py [OPTIONS] NAME                                       
                                                                     
 Say hi to NAME, optionally with a --lastname.
 If --formal is used, say hi very formally.                          

╭─ Arguments ───────────────────────────────────────────────────────╮
│ *    name      TEXT  [default: None] [required]                   │
╰───────────────────────────────────────────────────────────────────╯
╭─ Options ─────────────────────────────────────────────────────────╮
│ --lastname                             TEXT                       │
│ --formal                --no-formal          [default: no-formal] │
│ --help                                       Show this message    │
│                                              and exit.            │
╰───────────────────────────────────────────────────────────────────╯

CLI Arguments

Before, you had this function parameter:

Code
name: str

And now we wrap it with Annotated:

Code
name: Annotated[str]

Both of these versions mean the same thing, Annotated is part of standard Python and is there for this.

But the second version using Annotated allows us to pass additional metadata that can be used by Typer (it com Annotated comes from the typing module (PEP 593)):

Code
name: Annotated[str, typer.Argument()]

Now we are being explicit that name is a CLI argument. It's still a str and it's still required (it doesn't have a default value).

How it works internally

See Annotations for more informaiton

Python stores this in __annotations__:

Code
print(main.__annotations__)

You’d see something like:

Code
{'name': typing.Annotated[str, Argument(...)]}

Typer inspects those annotations → sees Annotated[str, typer.Argument(...)] → and knows how to turn it into CLI parameters.

CLI Arguments with Help

You can use the help parameter to add a help text for a CLI argument:

python
import typer
from typing_extensions import Annotated


def main(name: Annotated[str, typer.Argument(help="The name of the user to greet")]):
    print(f"Hello {name}")


if __name__ == "__main__":
    typer.run(main)

CLI Options

CLI Options with Help

python
import typer
from typing_extensions import Annotated


def main(
    name: str,
    lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",
    formal: Annotated[bool, typer.Option(help="Say hi formally.")] = False,
):
    """
    Say hi to NAME, optionally with a --lastname.

    If --formal is used, say hi very formally.
    """
    if formal:
        print(f"Good day Ms. {name} {lastname}.")
    else:
        print(f"Hello {name} {lastname}")


if __name__ == "__main__":
    typer.run(main)

CLI Parameter Types

Data conversion

When you declare a CLI parameter with some type Typer will convert the data received in the command line to that data type.

CLI Option Name

You can pass the CLI option name that you want to have in the following positional argument passed to typer.Option():

python
import typer
from typing_extensions import Annotated


def main(user_name: Annotated[str, typer.Option("--name")]):
    print(f"Hello {user_name}")


if __name__ == "__main__":
    typer.run(main)

A short name is a CLI option name with a single dash (-) instead of 2 (--) and a single letter, like -n instead of --name.

For example, the ls program has a CLI option named --size, and the same CLI option also has a short name -s:

In Typer you can also define CLI option short names the same way you can customize the long names.

You can pass positional arguments to typer.Option() to define the CLI option name(s).

python
import typer
from typing_extensions import Annotated


def main(user_name: Annotated[str, typer.Option("--name", "-n")]):
    print(f"Hello {user_name}")


if __name__ == "__main__":
    typer.run(main)

CLI Option Callback and Context

In some occasions you might want to have some custom logic for a specific CLI parameter (for a CLI option or CLI argument) that is executed with the value received from the terminal.

In those cases you can use a CLI parameter callback function.

python
from typing import Optional

import typer
from typing_extensions import Annotated


def name_callback(value: str):
    if value != "Camila":
        raise typer.BadParameter("Only Camila is allowed")
    return value


def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):
    print(f"Hello {name}")


if __name__ == "__main__":
    typer.run(main)

Here you pass a function to typer.Option() or typer.Argument() with the keyword argument callback.

The function receives the value from the command line. It can do anything with it, and then return the value.

In this case, if the --name is not Camila we raise a typer.BadParameter() exception.

The BadParameter exception is special, it shows the error with the parameter that generated it.

Check it:

sh
python main.py --name Camila

Hello Camila

python main.py --name Rick

Usage: main.py [OPTIONS]

💬 We get the error from the callback
Error: Invalid value for '--name': Only Camila is allowed

Final Example

python
def list_topics(value: Annotated[str, typer.Option()]):
    if value is None:
        return value
    topics = value.split(",")
    for topic in topics:
        if topic not in TOPICS:
            raise typer.BadParameter(f"topic {topic} not recognized")
    return topics


def main(
    file: Annotated[str, 
                    typer.Argument(None, help="File to read, stdin otherwise")
                    ] = None,
    colorize: Annotated[bool, typer.Option("--color")] = True,
    n_columns: Annotated[int, typer.Option("--columns", "-c")] = None,
    ignore: Annotated[str, typer.Option("--ignore", "-i", callback=list_topics)] = None,
    just: Annotated[str, typer.Option("--just", "-j", callback=list_topics)] = None,
):
    # ...

Rich

See Welcome to Rich’s documentation! — Rich 14.1.0 documentation for full details.

Quick Start

python
# It will overwrite the built-in print function with Rich’s enhanced version.
from rich import print

If you would rather not shadow Python’s built-in print, you can import rich.print as rprint (for example):

python
from rich import print as rprint

You can then print strings or objects to the terminal in the usual way. Rich will do some basic syntax highlighting and format data structures to make them easier to read.

Strings may contain Console Markup which can be used to insert color and styles in to the output.

The following demonstrates both console markup and pretty formatting of Python objects:

python
print("[italic red]Hello[/italic red] World!", locals())

There is a shorthand for closing a style. If you omit the style name from the closing tag, Rich will close the last style. For example:

pyhton
print("[bold red]Bold and red[/] not bold or red")

python
print("[bold]Bold[italic] bold and italic [/bold]italic[/italic]")

Console API

Console API — Rich 14.1.0 documentation

For complete control over terminal formatting, Rich offers a Consoleclass. Most applications will require a single Console instance, so you may want to create one at the module level or as an attribute of your top-level object.

Columns

Columns — Rich 14.1.0 documentation

python
from rich.console import Console
from rich.columns import Columns

console = Console()

items = [
    "[red]Item 1[/]",
    "[green]Item 2[/]",
    "[blue]Item 3[/]",
    "[yellow]Item 4[/]",
    "[magenta]Item 5[/]",
]

console.print(Columns(items))

This will print all the items side by side in as many columns as fit your terminal width. If the terminal is too narrow, items will wrap to the next line.

Fixed Number of Columns

python
console.print(Columns(items, equal=True, expand=True))

  • equal=True → makes each column the same width.

  • expand=True → makes columns stretch to fill the full width.

Panel

A Panel is a box that surrounds some content (text or any other renderable) with a border, optional title, and styling.

python
from rich.console import Console
from rich.panel import Panel

console = Console()

panel = Panel("S0 T3 Received AppendEntries from 2 with term 3", title="peer S0")
console.print(panel)

Result:

Code
╭───────────────── peer S0 ─────────────────╮
│ S0 T3 Received AppendEntries from 2 with  │
│ term 3                                    │                                             
╰───────────────────────────────────────────╯         

UV

An extremely fast Python package and project manager, written in Rust.

--help

Code
saber@Saber:~/cs336-A1$ uv --help
An extremely fast Python package manager.

Usage: uv [OPTIONS] <COMMAND>

Commands:
  auth     Manage authentication
  run      Run a command or script
  init     Create a new project
  add      Add dependencies to the project
  remove   Remove dependencies from the project
  version  Read or update the project's version
  sync     Update the project's environment
  lock     Update the project's lockfile
  export   Export the project's lockfile to an alternate format
  tree     Display the project's dependency tree
  format   Format Python code in the project
  tool     Run and install commands provided by Python packages
  python   Manage Python versions and installations
  pip      Manage Python packages with a pip-compatible interface
  venv     Create a virtual environment
  build    Build Python packages into source distributions and wheels
  publish  Upload distributions to an index
  cache    Manage uv's cache
  self     Manage the uv executable
  help     Display documentation for a command
...

Install python using uv

sh
uv python install 3.12

See what's installed: uv python list

Find where Python is: uv python find

Change python version for a project

Code
# Tell uv to use Python 3.11 for this folder
uv python pin 3.11

If your project is managed via pyproject.toml, you should also update the version requirement there to ensure consistency:

Code
requires-python = ">=3.11"

Run a single python script without dependency

sh
uv run main.py

Working on projects

Working on projects | uv

uv supports managing Python projects, which define their dependencies in a pyproject.toml file.

Creating a new project

sh
uv init hello-world
cd hello-world

Alternatively, you can initialize a project in the working directory:

Code
mkdir hello-world
cd hello-world
uv init

Managing dependencies

You can add dependencies to your pyproject.toml with the uv add command. This will also update the lockfile and project environment:

Code
uv add requests

If you have requirements.txt and you want to import thsi dependencies, you can

Code
uv add -r requirements.txt

Check installed dependency

Local project

If you want to see exactly which packages and versions are currently installed in your active virtual environment (.venv), use:

sh
uv pip list

If you want to see not just what is installed, but why it was installed (which package required which dependency), use:

Code
uv tree

Loguru

https://loguru.readthedocs.io/

Basic

The main concept of Loguru is that there is one and only one logger.

For convenience, it is pre-configured and outputs to stderr to begin with (but that’s entirely configurable)!!!!!

python
from loguru import logger

logger.debug("Debugging details")
logger.info("General info")
logger.success("It worked!")
logger.warning("Something is fishy")
logger.error("Something went wrong")
logger.critical("The system is down!")

No Handler, no Formatter, no Filter: one function to rule them all

How to add a handler? How to set up logs formatting? How to filter messages? How to set level?

One answer: the add() function.

python
logger.add(sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO")

This function should be used to register sinks which are responsible for managing log messages contextualized with a record dict.

Modern string formatting using braces style

python
logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")

Example

python
import sys
from loguru import logger

# Get rid of the default plain formatting
logger.remove() 

# Add a new format
# use level to filter some noisy messages
# logger.add(sys.stdout, 
#            colorize=True, 
#            level="WARNING",
#            format=  "{time: HH:mm:ss} " \
#                     "{level: <10} " \
#                     "{name: <8} " \
#                     "{function: <8} " \
#                     "{line: <3} "
#                     "<level>{message}</level>")

# ------------ filter --------
# 1. How the Filter Works
# The filter parameter in logger.add() accepts a function. 
# This function receives a Record (a dictionary containing 
# all the metadata about the log) and must return True 
# (to log it) or False (to drop it).

# The Record Dictionary
# To write a good filter, you need to know what’s inside the record. Here are the most common keys:
# record["name"]: The name of the module (e.g., __main__ or utils.db).
# record["level"].name: The level as a string (e.g., "DEBUG").
# record["message"]: The actual text of the log.
# record["extra"]: Any data you passed using .bind().

def customFilter(record):
    return "saber" in record["message"].lower()

logger.add(sys.stdout, 
           colorize=True, 
           level="WARNING",
        #    filter= lambda record: record["name"] == "__main__" ,
            filter = customFilter,
           format=  "{time: HH:mm:ss} " \
                    "{level: <10} " \
                    "{name: <8} " \
                    "{function: <8} " \
                    "{line: <3} "
                    "<level>{message}</level>")

# ----------- format -----------
# {time}	The current timestamp (supports custom formatting like YYYY-MM-DD)
# {level}	The severity level (INFO, DEBUG, etc.)
# {message}	The actual text you logged
# {name}	The module name (e.g., main)
# {function}	The function name where the log was called
# {line}	The line number
# {extra}	Any data passed via .bind()

# ----------- align -----------
# Inside your curly braces { }, you can specify a minimum 
# width and the alignment using the : syntax.

# {token: <10}: Left-aligned, minimum 10 characters.
# {token: >10}: Right-aligned, minimum 10 characters.
# {token: ^10}: Center-aligned, minimum 10 characters.


# NOTE: it will output to stderr!
logger.debug("Debugging details")
logger.info("General info")
logger.success("It worked!")
logger.warning("Something is fishy")
logger.error("Something went wrong")
logger.critical("The system Saber is down!")

Awkward

Turn to ak.array

python
data = ak.Array(data)

ak.flatten

Think of ak.flatten as an eraser that specifically rubs out the brackets [] separating your nested lists. It takes lists of lists and merges them into a single continuous sequence at that specific level.

By default, it operates on axis=1, meaning it erases the boundaries of the first layer of inner lists.

python
import awkward as ak

# An array with 3 sub-lists (one is empty)
arr = ak.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]])

# Erase the boundaries of the inner lists
flat_arr = ak.flatten(arr)

print(flat_arr)
# Output: <Array [1.1, 2.2, 3.3, 4.4, 5.5] type='5 * float64'>

So if the shape of array is (a, b, c, d,...), Then flatten along axis = c will change it to (a, b*c, d,...). I.e., merge current dimension with previous dimension.

The axis=0 Exception

In Awkward Array, axis=0 represents the very outermost boundary of your entire dataset. Because there is no container "above" axis=0 to merge lists into, ak.flatten(arr, axis=0) cannot actually flatten lists together.

Instead, Awkward Array uses axis=0 for one specific job: removing missing data (None) from the top level.

Code Example

If you have an array where an entire subject or trial failed to record and is marked as None, axis=0 will cleanly filter it out without touching the rest of your inner data structure.

Python

python
import awkward as ak

# Notice the 'None' sitting at the top level between the lists
arr = ak.Array([[1.1, 2.2], None, [3.3], [], [4.4, 5.5]])

# "Flatten" axis 0
clean_arr = ak.flatten(arr, axis=0)

print(clean_arr)
# Output: <Array [[1.1, 2.2], [3.3], [], [4.4, 5.5]] type='4 * var * float64'>

Notice how the None is gone, but the nested brackets [] are completely untouched!

Back to list

python
data = data.to_list()

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.