Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- String Formatting
- Indexing and Slicing
- Set Comprehensions
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Python Core Concepts
Python Collections
- Python collections ChainMap
- Python collections
- Python collections ChainMap<
- Python counters
- Python deque
- Python dictionary
- Python Lists
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
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
- List Iteration
- Dictionary Iteration
- Set Iteration
- Differences Between These Structures
- Looping Techniques and Best Practices
- Practical Examples
- Common Mistakes and Fixes
- 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
Feature | List | Dictionary | Set |
---|---|---|---|
Ordered | ✅ Yes | ❌ No | ❌ No |
Duplicates | ✅ Allowed | ❌ (unique keys) | ❌ Not Allowed |
Indexing | ✅ Yes | ❌ No | ❌ No |
Iterable Items | Elements | Keys, Values, Items | Elements |
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 withrange(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!