Looping Through Different Data Structures
3. Lists, Strings, and More!
The beauty of the 'for' loop is its versatility. It can be used to iterate through a wide variety of data structures, not just lists. Let's explore some common examples.
Lists: As we saw earlier, iterating through a list is straightforward. The 'for' loop simply assigns each element in the list to the loop variable in sequence. You can then perform any operation on the loop variable within the loop's body. For example, you could calculate the square of each number in a list:
numbers = [1, 2, 3, 4, 5]for number in numbers: square = number
number print(f"The square of {number} is {square}")
Strings: You can also iterate through a string, treating it as a sequence of characters. The loop will assign each character in the string to the loop variable. For instance:
message = "Hello"for char in message: print(char)
This will output:
Hello
You could then, say, count the vowels or find specific characters in the string.
Tuples: Tuples are similar to lists, but they are immutable (cannot be changed after creation). You can iterate through a tuple just like a list. The 'for' loop will assign each element in the tuple to the loop variable in sequence.
Dictionaries: Looping through dictionaries is a bit different. By default, a 'for' loop will iterate through the keys* of the dictionary. If you want to access the values, you can use the `dictionary.values()` method. If you want to access both the keys and values, you can use the `dictionary.items()` method, which returns a sequence of (key, value) pairs. For example:
student = {"name": "Alice", "age": 20, "major": "Computer Science"}for key, value in student.items(): print(f"Key: {key}, Value: {value}")
This will output:
Key: name, Value: AliceKey: age, Value: 20Key: major, Value: Computer Science
Using the range()
Function with 'for' Loops
4. Generating Sequences on the Fly
The `range()` function is a powerful tool that often goes hand-in-hand with 'for' loops. It allows you to generate a sequence of numbers, which can be incredibly useful for controlling the number of iterations in a loop.
The basic syntax of `range()` is `range(start, stop, step)`. 'start' is the starting number of the sequence (inclusive), 'stop' is the ending number of the sequence (exclusive), and 'step' is the increment between numbers. If you omit 'start', it defaults to 0. If you omit 'step', it defaults to 1.
For example, `range(5)` will generate the sequence 0, 1, 2, 3, 4. `range(1, 10)` will generate the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9. And `range(0, 20, 2)` will generate the sequence 0, 2, 4, 6, 8, 10, 12, 14, 16, 18.
You can use `range()` within a 'for' loop to repeat a block of code a specific number of times. For example, to print "Hello!" five times, you could write:
for i in range(5): print("Hello!")
Notice that the loop variable `i` takes on the values 0, 1, 2, 3, and 4. While we don't actually use the value of `i` in this example, it's often useful to have access to the current iteration number within the loop.