Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

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).

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.

Output
[20, 40, 60, 80, 100]

Comprehension with Filtering

Adding an if statement to filter data instantly.

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).

Output
{1300: 'NCR', 1400: 'CAR', 100: 'Region I'}
Code 1400 belongs to: CAR