Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Python Core Concepts

Python Collections

Python Programs


List, Dictionary, and Set Iterations in Python

Python is a highly versatile language known for its simple syntax and powerful data structures. Among the most commonly used are lists, dictionaries, and sets — each with unique characteristics and use cases.

A big part of working with these data structures is being able to iterate over them — in other words, loop through their contents. Whether you’re building a data scraper, parsing a file, or just printing names from a list, you’ll frequently use loops and iteration techniques.

In this guide, you’ll explore how to iterate over lists, dictionaries, and sets, understand their differences, and apply them effectively in real-world scenarios.


📌 Why Learn About Iteration?

Iteration is one of the most fundamental programming concepts. In Python:

  • Lists allow ordered, repeatable access.
  • Dictionaries offer key-value access.
  • Sets provide unordered, unique items.

Knowing how to loop through each structure efficiently helps you build more flexible, readable, and maintainable code.


🧠 Prerequisites

Before diving in, you should know:

  • Basic Python syntax
  • How to define a list, dictionary, and set
  • What a for loop is and how it works

If you’ve written for item in my_list: before, you’re good to go.


🧭 What This Guide Covers

  1. List Iteration
  2. Dictionary Iteration
  3. Set Iteration
  4. Differences Between These Structures
  5. Looping Techniques and Best Practices
  6. Practical Examples
  7. Common Mistakes and Fixes
  8. Conclusion

🔢 1. Iterating Over Lists

A list is an ordered, indexable collection of items. Here’s the most basic way to loop through one:

✅ Example:

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
    print(fruit)

📌 Output:

apple
banana
cherry

You can also use index-based iteration using range():

for i in range(len(fruits)):
    print(f"Index {i}: {fruits[i]}")

💡 List Comprehensions (Compact Iteration)

upper_fruits = [fruit.upper() for fruit in fruits]
print(upper_fruits)

📘 2. Iterating Over Dictionaries

Dictionaries are unordered collections of key-value pairs. You can iterate over keys, values, or both.

✅ Example 1: Looping through keys

person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

for key in person:
    print(key)

✅ Example 2: Looping through values

for value in person.values():
    print(value)

✅ Example 3: Looping through key-value pairs

for key, value in person.items():
    print(f"{key} = {value}")

🌱 3. Iterating Over Sets

A set is an unordered collection of unique elements. It’s useful for removing duplicates and checking membership.

✅ Example:

colors = {'red', 'green', 'blue'}

for color in colors:
    print(color)

⚠️ Note: The order of items in a set is not guaranteed!

Sets are useful when you don’t care about the order and want to avoid duplicate values.


🔄 4. Comparison Table

FeatureListDictionarySet
Ordered✅ Yes❌ No❌ No
Duplicates✅ Allowed❌ (unique keys)❌ Not Allowed
Indexing✅ Yes❌ No❌ No
Iterable ItemsElementsKeys, Values, ItemsElements
Mutability✅ Mutable✅ Mutable✅ Mutable

🔁 5. Advanced Looping Techniques

Loop with enumerate()

Use this to get both index and value in a list:

names = ['Tom', 'Jerry', 'Spike']

for index, name in enumerate(names):
    print(index, name)

Loop with zip()

Used to iterate over two lists at the same time:

names = ['Tom', 'Jerry']
scores = [90, 85]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")

Looping with sorted() and reversed()

# Sorting a set before iteration
for item in sorted(colors):
    print(item)

# Reverse a list
for item in reversed(fruits):
    print(item)

🧪 6. Practical Use Cases

✅ Example 1: Counting Items in a List

animals = ['dog', 'cat', 'dog', 'parrot']
animal_count = {}

for animal in animals:
    animal_count[animal] = animal_count.get(animal, 0) + 1

print(animal_count)

✅ Example 2: Filtering Values in a Dictionary

grades = {'John': 85, 'Jane': 92, 'Doe': 76}

for student, grade in grades.items():
    if grade > 80:
        print(f"{student} passed!")

✅ Example 3: Removing Duplicates with Sets

emails = ['a@example.com', 'b@example.com', 'a@example.com']
unique_emails = set(emails)

for email in unique_emails:
    print(email)

🚫 7. Common Mistakes to Avoid

  • Modifying a list while iterating: Always create a copy or use list comprehension instead.

    for item in my_list[:]:  # Use a slice copy
        if item == "remove":
            my_list.remove(item)
  • Relying on order in a dictionary or set: Remember, these are unordered by nature.

  • Accessing set elements by index: You can’t do this, unlike lists.


🌟 8. Best Practices

  • Use list comprehensions for short and clean iterations.
  • Use .items() in dictionaries to access both key and value.
  • Convert sets to lists if you need indexing or order.
  • Prefer enumerate() over manual indexing with range(len(...)).

Iteration is a powerful tool in Python and knowing how to efficiently loop through lists, dictionaries, and sets will take you a long way. Whether you’re counting values, filtering data, or removing duplicates, mastering these basic structures can help you write cleaner and more efficient code.

Python’s elegance shines in its iteration tools — so the more you practice, the more “Pythonic” your code will become!