Iterating over data is a fundamental operation in many data processing and analysis tasks. In Python, you can use a for loop or a while loop to iterate over data in various forms, such as lists, tuples, dictionaries, sets, and files.
Here's an example of how to iterate over a list of numbers using a for loop:
numbers = [1, 2, 3, 4, 5]for num in numbers: print(num) |
In this example, we define a list of numbers and loop over each element using the for loop. The num variable takes on the value of each element in the list, and we print it to the console using the print() function.
You can use a similar approach to iterate over other data types, such as tuples, dictionaries, and sets. Here's an example of how to iterate over a dictionary of names and ages using a for loop:
person = {'name': 'Alice', 'age': 25}for key, value in person.items(): print(f'{key}: {value}') |
In this example, we define a dictionary with keys 'name' and 'age' and loop over each key-value pair using the for loop. The key variable takes on the value of each key in the dictionary, and the value variable takes on the value of each corresponding value. We print each key-value pair using formatted string literals.
You can also use a while loop to iterate over data, especially when you need more control over the loop's termination condition. Here's an example of how to read lines from a file using a while loop:
|
with open('data.txt') as f:
line = f.readline()
while line:
print(line.strip())
line = f.readline()
|
In this example, we open a file named 'data.txt' using the with statement to automatically close the file after the loop. We read the first line of the file using the readline() method and store it in the line variable. We then enter a while loop that continues as long as line is not an empty string. Inside the loop, we print the stripped line to the console and read the next line using readline().