Nearby lessons

46 of 159

Python - For Loop with Collections

📌 What You Will Learn
  • Iterate over every element of a list, tuple, set and dictionary with a for loop
  • Filter list elements with an if statement inside a loop
  • Display positive and negative indices using len() and range()
  • Use d[x] to print dictionary values and items() to get both keys and values
  • Understand that a set is unordered so its output order may change

for Loop with List

If we want to execute an action for every element present in a list, we use the for loop.

Example 1 - Print All Elements of a List

Loading editor…

Explanation

The loop visits every element of the list one by one.

Example 2 - Print Only Even Numbers

Loading editor…

Explanation

The if statement filters only the even numbers.

Example 3 - Display Positive and Negative Index

Loading editor…

Understanding the Program

  • len(l) returns the total number of elements in the list.
  • range(x) generates index values from 0 to x-1.
  • l[i] accesses the list element using its index.
  • i-x gives the corresponding negative index.

for Loop with Tuple

A tuple is also a sequence, so we can use the for loop to access each element one by one.

Example 1 - Print Tuple Elements

Loading editor…

Example 2 - Find Sum of Tuple Elements

Loading editor…

for Loop with Set

A set is also iterable. We can access every element using the for loop.

Since a set is unordered, the output order may change every time the program runs.

Example 1 - Print Set Elements

Loading editor…

Explanation

The order of elements in a set is not fixed.

Therefore, the output order may be different on different executions.

Example 2 - Print Squares of Set Elements

Loading editor…

for Loop with Dictionary

A dictionary stores data as key : value pairs.

By default, the for loop iterates through dictionary keys.

Example 1 - Print Dictionary Keys

Loading editor…

Explanation

When a dictionary is directly used inside a for loop, only the keys are returned.

Example 2 - Print Dictionary Values

Loading editor…

Example 3 - Print Keys and Values

Loading editor…

Explanation

The items() method returns both keys and values.

This is the most common way to iterate through a dictionary.

📝 Key Takeaways
  • A dictionary returns its keys by default when used directly in a for loop
  • The items() method returns both keys and values of a dictionary
  • Sets are unordered, so the output order may change on each execution
  • range(len(l)) generates valid index positions for a list
  • A for loop can only read tuple elements because tuples are immutable

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.