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).
1# Creating a list of sensor readings2readings = [23.5, 24.1, 23.8, 25.0]34# Accessing elements (0-indexed)5print(readings[0]) # Prints 23.56print(readings[-1]) # Prints 25.0 (negative index counts from the end)78# Modifying the list9readings.append(26.2) # Adds to the end10readings.pop(0) # Removes the first itemList Comprehensions (Advanced but Common)
You will often see lists created dynamically in Python using a one-liner called a List Comprehension.
1# Create a list of the squares of numbers from 0 to 92squares = [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.
1# Create a dictionary2sensor = {3 "type": "BME280",4 "temperature": 25.4,5 "active": True6}78# Access data using the key9print(sensor["type"]) # Output: BME2801011# Modify data12sensor["temperature"] = 26.11314# Add new data15sensor["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.
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}1314# 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.
1import json23# A raw JSON string (e.g., received over MQTT)4payload = '{"temperature": 24.5, "humidity": 60}'56# Parse the JSON string into a Python Dictionary7data_dict = json.loads(payload)89print(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.
1# Tuples use parentheses () instead of brackets []2resolution = (1920, 1080)34# resolution[0] = 1280 <-- This would cause a TypeError!56# You can "unpack" tuples instantly into variables7width, height = resolution8print(f"Width: {width}")
