Learn Python: The Fundamentals

In Python, you can loop through all kinds of collections — lists, dictionaries, strings, and more — in a way that’s both simple and readable. Instead of tracking positions manually, Python offers helpful tools like enumerate() and .items() to make your loops cleaner and more powerful.

 

Looping Through Lists, Strings, and Dictionaries

 

# Looping through a list using enumerate
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")   # Adds a number before each fruit

# Looping through a string, one character at a time
message = "Hi!"
for ch in message:
    print(ch)

# Looping through a dictionary's key–value pairs
person = {"name": "Alice", "age": 25, "city": "Sydney"}
for key, value in person.items():
    print(f"{key}: {value}")

 

Notice how enumerate() gives you both the index and the item when looping through a list — no need to manage counters manually. Similarly, .items() lets you easily loop through both keys and values in a dictionary.

 

Building Useful Summaries

You can use loops not just to process data, but to turn it into helpful summaries or reports. If you’re working with a list of dictionaries, unpack values as you go to keep your code clean.

 

# A list of user profiles
users = [
    {"username": "tyler", "role": "student", "active": True},
    {"username": "maya", "role": "mentor", "active": False},
]

for u in users:
    status = "Active" if u["active"] else "Inactive"
    print(f"- {u['username']} ({u['role']}) — {status}")

 

Interactive Exercise: Print Tasks and Profile

This exercise combines everything above. Loop through a list and a dictionary to generate a readable summary. Try adding more data and re-run the program — it should still work!

 


tasks = ["Install Python", "Write a script", "Run tests", "Push to repo"]
user = {"username": "tyler", "role": "student", "active": True}

print("TASKS:")
for i, t in enumerate(tasks, start=1):
print(f"{i}) {t}")

print("\nUSER PROFILE:")
for k, v in user.items():
print(f"{k}: {v}")

# Try adding:
# tasks.append("Open a PR")
# user["timezone"] = "Australia/Sydney"

 
Use enumerate() for position-based lists, and .items() for key–value pairs.
 

Looping through collections is one of Python’s most useful skills. Once you master it, you’ll be able to write cleaner code that adapts easily as your data grows or changes.