Python

Iteration

For-Each Loop

Iterates directly over the values in a sequence. This is the most common loop form in Python and should be used when the index is not needed.

items = ["hello","world"]
for item in items:
    print(item)

Range-Based Iteration (range)

Iterates over a sequence of integers. This is commonly used for fixed-count loops or when generating index values without an existing sequence.

for i in range(5):
    print(i)

Index-Based Iteration (enumerate)

Provides access to both the index and the value during iteration. This is the canonical Python pattern when the position of an item matters.

items = ["hello", "world"]
for index, item in enumerate(items):
    print(index, item)

Parallel Iteration (zip)

Iterates over multiple sequences in parallel, yielding one value from each sequence per iteration. Iteration stops at the shortest sequence.

names = ["alice", "bob", "carol"]
scores = [10, 20, 30]

for name, score in zip(names, scores):
    print(name, score)

Json Data

Python includes built-in support for converting between JSON text and native Python data structures. Parsing reads JSON text into memory as dictionaries and lists, while serialization converts Python values back into JSON text. Pretty serialization formats the output for readability.

Parse JSON

Parsing JSON converts a JSON-formatted string into Python data structures. This is commonly used when reading JSON from files, APIs, or external input.

import json

json_text = '{"name":"John","active":true,"count":3}'

data = json.loads(json_text)

print(data["name"])  # "John"

Serialize JSON

Serializing JSON converts Python data structures into a JSON-formatted string. This is used when writing data to files, sending data over a network, or storing structured information.

import json

data = {
    "name": "John",
    "active": True,
    "count": 3
}

json_text = json.dumps(data)

print(json_text)
# {"name": "John", "active": true, "count": 3}

Pretty Serialize JSON

Pretty serialization formats JSON output with indentation and line breaks. This improves readability and is commonly used for configuration files, logs, and debugging.

import json

data = {
    "name": "John",
    "active": True,
    "count": 3
}

pretty_json = json.dumps(data, indent=4)
print(pretty_json)

'''
{
    "name": "John",
    "active": true,
    "count": 3
}
'''

Provider