What can you iterate over using a for loop in Python?

QuestionsQuestions8 SkillsProPython Control StructuresAug, 23 2025
0240

In Python, you can iterate over several types of objects using a for loop, including:

  1. Lists: You can iterate over the elements of a list.

    my_list = [1, 2, 3, 4]
    for item in my_list:
        print(item)
  2. 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)
  3. Strings: You can iterate over each character in a string.

    my_string = "Hello"
    for char in my_string:
        print(char)
  4. 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
  5. Sets: You can iterate over the elements of a set.

    my_set = {1, 2, 3, 4}
    for item in my_set:
        print(item)
  6. Files: You can iterate over the lines in a file.

    with open('myfile.txt') as f:
        for line in f:
            print(line)
  7. 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.

0 Comments

no data
Be the first to share your comment!