Python Refresher

Data Structures

Python shines when it comes to handling collections of data. You don't need to write complex pointer logic to manage arrays; Python has powerful, built-in data structures.


Lists

A List is an ordered, changeable collection of items. In Python, a list can hold different types of data at the same time (though for ML, we usually keep them uniform).

python
1# Creating a list of sensor readings
2readings = [23.5, 24.1, 23.8, 25.0]
3
4# Accessing elements (0-indexed)
5print(readings[0]) # Prints 23.5
6print(readings[-1]) # Prints 25.0 (negative index counts from the end)
7
8# Modifying the list
9readings.append(26.2) # Adds to the end
10readings.pop(0) # Removes the first item

List Comprehensions (Advanced but Common)

You will often see lists created dynamically in Python using a one-liner called a List Comprehension.

python
1# Create a list of the squares of numbers from 0 to 9
2squares = [x**2 for x in range(10)]
3print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Dictionaries (Key-Value Pairs)

Dictionaries store data like a real-world dictionary: you look up a "key" (a word) to find its "value" (the definition). In other languages, these are called Hash Maps or JSON objects.

python
1# Create a dictionary
2sensor = {
3 "type": "BME280",
4 "temperature": 25.4,
5 "active": True
6}
7
8# Access data using the key
9print(sensor["type"]) # Output: BME280
10
11# Modify data
12sensor["temperature"] = 26.1
13
14# Add new data
15sensor["location"] = "Living Room"

Real-World Example: Nested Dictionaries

When you receive data from an API (like checking the weather on the internet), it usually comes in a heavily nested dictionary.

python
1weather_api_response = {
2 "status": 200,
3 "location": "Bangalore",
4 "data": {
5 "temperature": 28.5,
6 "humidity": 65,
7 "wind": {
8 "speed": 12.5,
9 "direction": "NE"
10 }
11 }
12}
13
14# How to extract the wind speed?
15# Chain the keys together!
16wind_spd = weather_api_response["data"]["wind"]["speed"]
17print(f"Wind speed is {wind_spd} km/h")

Parsing JSON

Because Dictionaries map 1:1 with JSON, Python makes it trivial to parse JSON data received from a web API or MQTT broker.

python
1import json
2
3# A raw JSON string (e.g., received over MQTT)
4payload = '{"temperature": 24.5, "humidity": 60}'
5
6# Parse the JSON string into a Python Dictionary
7data_dict = json.loads(payload)
8
9print(f"The temperature is {data_dict['temperature']}")

Tuples

A Tuple is like a List, but it is immutable (unchangeable). Once created, you cannot add, remove, or modify elements. They are useful for returning multiple values from a function or storing fixed coordinates.

python
1# Tuples use parentheses () instead of brackets []
2resolution = (1920, 1080)
3
4# resolution[0] = 1280 <-- This would cause a TypeError!
5
6# You can "unpack" tuples instantly into variables
7width, height = resolution
8print(f"Width: {width}")
Previous
Basics & Syntax