In Python, you can iterate over several types of objects using a for loop, including:
-
Lists: You can iterate over the elements of a list.
my_list = [1, 2, 3, 4] for item in my_list: print(item) -
Tuples: Similar to lists, you can iterate over the elements of a tuple.
my_tuple = (1, 2, 3, 4) for item in my_tuple: print(item) -
Strings: You can iterate over each character in a string.
my_string = "Hello" for char in my_string: print(char) -
Dictionaries: You can iterate over the keys, values, or key-value pairs in a dictionary.
my_dict = {'a': 1, 'b': 2} for key in my_dict: print(key, my_dict[key]) # Iterating over keys for value in my_dict.values(): print(value) # Iterating over values for key, value in my_dict.items(): print(key, value) # Iterating over key-value pairs -
Sets: You can iterate over the elements of a set.
my_set = {1, 2, 3, 4} for item in my_set: print(item) -
Files: You can iterate over the lines in a file.
with open('myfile.txt') as f: for line in f: print(line) -
Ranges: You can iterate over a range of numbers using the
range()function.for i in range(5): print(i) # Prints numbers from 0 to 4
These are some of the common objects you can iterate over using a for loop in Python.
