Can I iterate over other data types?

QuestionsQuestions8 SkillsProPython Control StructuresNov, 19 2025
0132

Yes, you can iterate over various data types in Python using a for loop. Here are some common data types that support iteration:

  1. Lists: As previously discussed, you can iterate over lists.

    fruits = ["apple", "banana", "cherry"]
    for fruit in fruits:
        print(fruit)
  2. Tuples: Similar to lists, you can iterate over tuples.

    colors = ("red", "green", "blue")
    for color in colors:
        print(color)
  3. Strings: You can iterate over each character in a string.

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

    unique_numbers = {1, 2, 3}
    for number in unique_numbers:
        print(number)
  6. 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!

0 Comments

no data
Be the first to share your comment!