In Python, iterating refers to the process of looping through elements in a sequence or collection one by one. Python provides several ways to iterate over data, such as lists, tuples, dictionaries, sets, strings, and more. Here are some common methods for iterating in Python:
For loop: The for
loop is used to iterate over a sequence (like lists, tuples, strings, etc.) or any iterable object.
for variable in iterable:
# Code block to be executed for each element in the iterable
While loop: The while
loop is used when you want to iterate based on a condition. The loop continues until the condition becomes False
.
while condition:
# Code block to be executed while the condition is True
Using range()
function with a for loop: The range()
function generates a sequence of numbers and is often used with a for
loop to iterate a specific number of times.
for variable in range(start, stop, step): # Code block to be executed for each value in the range
Using enumerate()
with a for loop: The enumerate()
function is used to iterate over a sequence while keeping track of the index as well.
for index, value in enumerate(iterable):
# Code block to be executed for each index-value pair
These are the basic syntaxes for iterating in Python. Depending on the specific situation and the type of data you want to iterate over, you can choose the appropriate loop construct to achieve your desired outcome.
Python Iterating examples
Here are some examples of common methods for iterating in Python:
1. Using a for loop:
# Iterating over a list
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
# Iterating over a string
my_string = "Hello, World!"
for char in my_string:
print(char)
# Iterating over a dictionary (keys)
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key)
# Iterating over a dictionary (values)
for value in my_dict.values():
print(value)
# Iterating over a dictionary (keys and values)
for key, value in my_dict.items():
print(key, value)
2. Using the range()
function:
for i in range(5):
print(i) # Outputs 0, 1, 2, 3, 4
3. Using enumerate()
:
my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
print(index, value)
4. Using while
loop:
count = 0
while count < 5:
print(count)
count += 1
5. Using list comprehensions:
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Outputs: [1, 4, 9, 16, 25]
Here’s an example of iterating through a list using a for
loop and enumerate()
:
# Example list
fruits = ['apple', 'banana', 'orange', 'grape']
# Using a for loop to iterate through the list
print("Using for loop:")
for fruit in fruits:
print(fruit)
# Using enumerate() to get both the index and value
print("\nUsing enumerate:")
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Output:
In the first loop, we simply iterate through the list fruits
using a for
loop, and in the second loop, we use enumerate()
to get both the index and the value of each element in the fruits
list. The enumerate()
function returns a tuple with the index and the value, so we use two variables (index
and fruit
) to unpack the tuple and print the results.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.