Yes, you can iterate over various data types in Python using a for loop. Here are some common data types that support iteration:
-
Lists: As previously discussed, you can iterate over lists.
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) -
Tuples: Similar to lists, you can iterate over tuples.
colors = ("red", "green", "blue") for color in colors: print(color) -
Strings: You can iterate over each character in a string.
word = "hello" for char in word: print(char) -
Dictionaries: You can iterate over keys, values, or key-value pairs in a dictionary.
data = {"name": "Alice", "age": 25} for key in data: print(key, data[key]) # Iterating over keys for value in data.values(): print(value) # Iterating over values for key, value in data.items(): print(key, value) # Iterating over key-value pairs -
Sets: You can iterate over elements in a set.
unique_numbers = {1, 2, 3} for number in unique_numbers: print(number) -
Files: You can iterate over lines in a file.
with open('file.txt', 'r') as file: for line in file: print(line.strip())
In summary, the for loop can be used to iterate over any iterable object in Python, making it a versatile tool for handling different data types. If you want to practice iterating over various data types, consider exploring related labs on LabEx!
