In Python, loops are used to iterate over various data structures such as ranges, lists, and other iterables. Iterables include objects that can return their elements one at a time, such as strings, tuples, dictionaries, and sets. This article provides examples of looping through ranges, lists, and other iterables.
The range() function is commonly used with loops to generate a sequence of numbers. It takes up to three arguments: start, stop, and step.
The following example demonstrates looping through a range of numbers:
# Looping through a range for i in range(1, 6): print(i)
Output:
1 2 3 4 5
Lists are one of the most commonly used data structures in Python. You can loop through each element in a list using a for loop.
The following example iterates through a list of fruits:
# Looping through a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
Output:
apple banana cherry
Strings are iterable, meaning you can loop through each character in a string.
The following example prints each character of a string:
# Looping through a string word = "Python" for char in word: print(char)
Output:
P y t h o n
Tuples, like lists, are iterable. You can loop through their elements just like you would with a list.
The following example iterates through a tuple:
# Looping through a tuple colors = ("red", "green", "blue") for color in colors: print(color)
Output:
red green blue
When looping through dictionaries, you can iterate over keys, values, or both using methods like .keys(), .values(), and .items().
The following example demonstrates looping through the keys and values of a dictionary:
# Looping through a dictionary person = {"name": "Alice", "age": 25, "city": "New York"} for key, value in person.items(): print(key, ":", value)
Output:
name : Alice age : 25 city : New York
Sets are unordered collections of unique elements. You can loop through their elements using a for loop.
The following example iterates through a set:
# Looping through a set unique_numbers = {1, 2, 3, 4, 5} for num in unique_numbers: print(num)
Output:
1 2 3 4 5
Python makes it easy to loop through ranges, lists, and other iterables. Understanding how to iterate over different types of data structures is a key skill in Python programming. Experiment with these examples to explore the versatility of loops in Python.