Iterations and Comprehensions
Iterations¶
Beyond standard for loops, Python provides powerful tools to iterate through data efficiently.
enumerate()¶
Use this when you need both the index (counter) and the value inside a loop.
# number the regions for a report
regions = ["NCR", "CAR", "Region I", "Region II"]
# `i` is the index, `region` is the value
for i, region in enumerate(regions, start=1):
print(f"Region Code {i}: {region}")Output
Region Code 1: NCR
Region Code 2: CAR
Region Code 3: Region I
Region Code 4: Region II
zip()¶
Used to iterate over two lists at the same time. This is common when you have separate columns of data (e.g., a list of provinces and a list of populations).
provinces = ["Cavite", "Laguna", "Batangas"]
populations = [4.3, 3.4, 2.9] # in millions
# Loop through both lists simultaneously
for prov, pop in zip(provinces, populations):
print(f"{prov} has a population of {pop} million")Output
Cavite has a population of 4.3 million
Laguna has a population of 3.4 million
Batangas has a population of 2.9 million
List Comprehensions¶
A concise way to create lists.
raw_data = [10, 20, 30, 40, 50]
doubled_data= [x * 2 for x in raw_data]
print(doubled_data)
# replaces these lines:
# doubled_data = []
# for x in raw_data:
# doubled_data.append(x * 2)Output
[20, 40, 60, 80, 100]
Comprehension with Filtering¶
Adding an if statement to filter data instantly.
# filter out negative entries
survey_ages = [25, 30, -1, 45, 0, 18, -99]
valid_ages = [age for age in survey_ages if age > 0]
print(f"Valid Ages: {valid_ages}")Output
Valid Ages: [25, 30, 45, 18]
Dictionary Comprehensions¶
Just like lists, you can build dictionaries in one line. This is great for remapping data (e.g., swapping keys and values).
# create a lookup dictionary for region codes
regions = ["NCR", "CAR", "Region I"]
codes = [1300, 1400, 100]
# create a dict: {1300: 'NCR', 1400: 'CAR', ...}
region_lookup = {code: name for code, name in zip(codes, regions)}
print(region_lookup)
print(f"Code 1400 belongs to: {region_lookup[1400]}")Output
{1300: 'NCR', 1400: 'CAR', 100: 'Region I'}
Code 1400 belongs to: CAR