Nearby lessons
46 of 159Python - For Loop with Collections
- 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
Explanation
The loop visits every element of the list one by one.
Example 2 - Print Only Even Numbers
Explanation
The if statement filters only the even numbers.
Example 3 - Display Positive and Negative Index
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-xgives 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
Example 2 - Find Sum of Tuple Elements
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
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
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
Explanation
When a dictionary is directly used inside a for loop, only the keys are returned.
Example 2 - Print Dictionary Values
Example 3 - Print Keys and Values
Explanation
The items() method returns both keys and values.
This is the most common way to iterate through a dictionary.
- 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