MODULE 01 · DAY 03 OF 40 · WEEK 1
> python_essentials_II.py

Collections

Lists· Tuples· Dicts· Sets· Comprehensions· Modules· File I/O
From Bits to Blockchain
MSBTE 315004 · Semester 5 · Final Year Diploma in Computer Science
# today: 1h lecture + 1h lab · goal: comprehensions over a transactions dataset
collections.py
M1·DAY 03·Recap → Today
02/14
02 // Where we left off → where we're going
Yesterday · Day 02

Python Essentials I

  • variables and core types
  • f-strings & string methods
  • if / elif / else, for, while
  • functions, parameters, return
Today · Day 03

Python Essentials II

  • the four collection types
  • list & dict comprehensions
  • modules and the import system
  • reading and writing files
Why these matter: every blockchain dataset you'll touch — blocks, transactions, balances, events — lives in lists of dicts.
M1·DAY 03·Overview
03/14
03//The four collections
One table, four mental models. Pick the right tool for the job.
TypeSyntaxOrdered? Mutable?Duplicates?Use it for…
list [1, 2, 3] yes yes yes ordered sequences you'll modify
tuple (1, 2, 3) yes no yes fixed records, function returns
dict {"k": v} yes yes keys: no key → value lookups (O(1))
set {1, 2, 3} no yes no uniqueness & membership tests
# ordered in Python 3.7+; in dicts that means insertion order is preserved
M1·DAY 03·Lists
04/14
04//Lists — ordered, mutable, your everyday workhorse
lists_demo.py
# block #4521 transaction hashes
tx_hashes = ["0xab12", "0xcd34", "0xef56"]

tx_hashes.append("0x7890")     # add at end
tx_hashes[0]                  # index → '0xab12'
tx_hashes[-1]                 # last  → '0x7890'
tx_hashes[1:3]                # slice
len(tx_hashes)             # count

# loop over them
for h in tx_hashes:
    print(h)
When to reach for a list
  • order matters
  • you'll add, remove, or sort items
  • duplicates are fine
  • you index by position, not name
Common methods
.append(x)add to end
.pop()remove last
.sort()sort in place
.reverse()flip order
inmembership test
M1·DAY 03·Tuples
05/14
05//Tuples — ordered, immutable, fixed-shape records
tuples_demo.py
# (sender, receiver, amount)
tx = ("alice", "bob", 12.5)

# unpacking — Pythonic & clean
sender, receiver, amount = tx

# functions can return many values
def min_max(values):
    return min(values), max(values)

lo, hi = min_max([3, 9, 1])

tx[0] = "eve"   # TypeError!
Why immutable helps
  • shape is locked — fewer bugs
  • safe as dict keys
  • function returns: many at once
  • slightly faster than lists
Mental model
list = a shopping cart
you keep adding & removing
tuple = a printed receipt
the record is finalized
M1·DAY 03·Dictionaries
06/14
06//Dictionaries — key → value, the JSON of Python
dicts_demo.py
# one transaction as a dict — the shape
# of every record on every blockchain
tx = {
    "sender":   "alice",
    "receiver": "bob",
    "amount":   150.0,
    "fee":      0.01,
}

tx["amount"]                  # 150.0
tx.get("memo", "")            # safe default
tx["confirmed"] = True
tx.keys();  tx.values()
Why dicts are fast
Lookup by key is O(1) — the same speed whether you have 10 items or 10 million.

That's why every blockchain RPC returns dicts.
Iterate over a dict
for k, v in tx.items():
    print(k, "->", v)
M1·DAY 03·Sets
07/14
07//Sets — unique items, fast membership tests
sets_demo.py
# every sender who appeared in block #4521
senders = ["alice", "bob", "alice", "eve"]

unique = set(senders)    # {'alice', 'bob', 'eve'}

# blazing-fast membership test — O(1)
"bob" in unique           # True

# set algebra works as math
block_a = {"alice", "bob"}
block_b = {"bob", "eve"}
block_a | block_b         # union
block_a & block_b         # intersection → {'bob'}
Reach for a set when…
  • you need to dedupe a list
  • you check membership often
  • you do union / intersection
  • order genuinely doesn't matter
On-chain use
Daily Active Addresses is just len(set(senders)) across a day's blocks.
M1·DAY 03·List Comprehensions
08/14
08//List comprehensions — the Pythonic for-loop
SYNTAX
[ expression  for item in iterable  if condition ]
# the if-clause is optional
Before · the long way
loop.py
amounts = [12, 200, 8, 450, 75]
big = []
for a in amounts:
    if a > 100:
        big.append(a)

# 5 lines, mutable accumulator
After · the comprehension
comp.py
amounts = [12, 200, 8, 450, 75]

big = [a for a in amounts if a > 100]

# 1 line, no accumulator
# → [200, 450]

# transform too — fees in paise
paise = [a * 100 for a in amounts]
M1·DAY 03·Dict Comprehensions
09/14
09//Dict comprehensions — build maps in one expression
SYNTAX
{ key_expr : value_expr  for item in iterable }
# also works with if-clauses
dict_comp.py
# list of tickers we follow
tickers = ["BTC", "ETH", "DOT", "SOL"]
prices  = [67000, 3400, 7.2, 145]

# zip + dict comprehension → ticker -> price
book = {t: p for t, p in zip(tickers, prices)}
# {'BTC': 67000, 'ETH': 3400, 'DOT': 7.2, 'SOL': 145}

# only the large-caps (price > 100)
large = {t: p for t, p in book.items() if p > 100}
M1·DAY 03·Modules & Imports
10/14
10//Modules & imports — borrow superpowers in one line
imports_demo.py
# 1. import the whole module
import hashlib
hashlib.sha256(b"hi").hexdigest()

# 2. import only what you need
from hashlib import sha256
sha256(b"hi").hexdigest()

# 3. give it a nickname
import pandas as pd
pd.DataFrame([{...}])

# your own file — same syntax
from wallet import sign_tx
Where modules come from
stdlib ships with Python
hashlib, json, os, math, random,
datetime, secrets
third-party installed via pip
pandas, requests, web3, substrate-interface
your code your own .py files
wallet.py, blockchain.py, utils.py
M1·DAY 03·Files
11/14
11//Reading & writing files — safely, with `with`
Text files
files_text.py
# write a log line
with open("chain.log", "w") as f:
    f.write("block #4521 ok\n")

# read it back, line by line
with open("chain.log") as f:
    for line in f:
        print(line.rstrip())

# 'with' auto-closes the file —
# even if an exception is raised.
JSON files
files_json.py
import json

block = {"number": 4521,
         "tx_count": 12}

# write JSON
with open("block.json", "w") as f:
    json.dump(block, f, indent=2)

# read JSON
with open("block.json") as f:
    data = json.load(f)
M1·DAY 03·Lab · Brief
12/14
12//Lab — transactions, the comprehension way
1 hr · no for loops where a comprehension fits
transactions.py · starter
transactions = [
  {"sender":"alice", "to":"bob",   "amount":150},
  {"sender":"bob",   "to":"eve",   "amount":50},
  {"sender":"alice", "to":"eve",   "amount":300},
  {"sender":"carol", "to":"alice", "amount":75},
  {"sender":"eve",   "to":"bob",   "amount":210},
  # …5 more — 10 transactions total
]
Your three tasks
01Total volume
Sum every amount across all 10 transactions. One comprehension + sum().
02Whales only
List of transactions where amount > 100. One list comprehension with an if-clause.
03Sender ledger
Build { sender: total_sent } across all transactions. One dict comprehension.
M1·DAY 03·Lab · Walkthrough
13/14
13//Lab walkthrough — three comprehensions
# we'll write all three live, then defaultdict-up #03
01 · Total volume
total = sum(t["amount"] for t in transactions)    # → 785
02 · Whales only (amount > 100)
whales = [t for t in transactions if t["amount"] > 100]
03 · Sender ledger { sender: total_sent }
# nested: for every unique sender, sum their amounts
ledger = {
    s: sum(t["amount"] for t in transactions if t["sender"] == s)
    for s in {t["sender"] for t in transactions}
}
M1·DAY 03·Wrap · Next
14/14
14//Wrap-up & what's next
Today you should be able to…
pick list vs tuple vs dict vs set fluently
filter & transform a list in one expression
build a dict from two parallel lists
import from stdlib, third-party, and your own files
read & write text and JSON safely with with
Tomorrow · Day 04
DSA — Lists & Strings
Big-O intuition · two-pointer technique · string manipulation patterns. We'll tackle interview-style problems on the same kinds of data structures we used today.
Before you close the laptop
Daily commit habit
$ git add . && git commit -m "day3: collections"
$ git push origin main
# 38 commits to go — the portfolio compounds
01 / 14
← → · F · ?

Keyboard shortcuts

→ Space next slide
← previous slide
Home first slide
End last slide
1–9 jump to slide
F fullscreen
? toggle this help
Esc close help