Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
The for
loop in Python is used to iterate over a sequence (such as a list, tuple, or string) or any other iterable object. It allows you to execute a block of code for each item in the sequence.
Here's a tutorial on how to use the for
loop statement in Python:
The basic syntax for the for
loop is as follows:
for variable in iterable: # code to execute for each item in the iterable
The variable
represents the current item in the iterable during each iteration. The iterable
can be any Python object that supports iteration, such as lists, tuples, strings, or dictionaries.
for
loop with a listHere's an example of using the for
loop with a list:
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
In this example, the for
loop iterates over the elements in the fruits
list and prints each element.
for
loop with a stringThe for
loop can also be used to iterate over the characters in a string:
text = "hello" for char in text: print(char)
In this example, the for
loop iterates over the characters in the text
string and prints each character.
for
loop with range()
The range()
function generates a sequence of numbers and can be used with a for
loop to iterate over a range of numbers:
for number in range(5): print(number)
In this example, the for
loop iterates over the numbers from 0 to 4 (5 not included) and prints each number.
You can also specify a start, stop, and step value for the range()
function:
for number in range(1, 10, 2): print(number)
In this example, the for
loop iterates over the odd numbers from 1 to 9 and prints each number.
for
loop with dictionariesTo iterate over the keys and values in a dictionary, you can use the .items()
method:
student = {"name": "John", "age": 21, "course": "Computer Science"} for key, value in student.items(): print(f"{key}: {value}")
In this example, the for
loop iterates over the key-value pairs in the student
dictionary and prints each key-value pair.
In summary, the for
loop statement in Python is a versatile and powerful tool that allows you to iterate over a sequence or an iterable object. It can be used with various data structures, such as lists, tuples, strings, and dictionaries. Understanding how to use for
loops effectively is essential for writing efficient and clean code in Python.
How to use for loop in Python:
for
loop to iterate over elements in a sequence or iterable.for item in iterable: # Loop logic for each item
Iterating over lists with for loop in Python:
for
loop.my_list = [1, 2, 3, 4, 5] for num in my_list: print(num)
Using range() function in Python for loop:
range()
and iterate over it with a for
loop.for i in range(5): print(i)
Nested for loops in Python:
for
loops to iterate over multiple sequences.for i in range(3): for j in range(2): print(i, j)
Iterating over dictionaries with for loop in Python:
for
loop.my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(key, value)
List comprehensions and for loops in Python:
for
loop.squared_numbers = [num**2 for num in range(5)] print(squared_numbers)
Common patterns for using for loop in Python:
# Iterating with an index for index, value in enumerate(my_list): print(index, value) # Reversing a list for item in reversed(my_list): print(item)
Looping through strings with for loop in Python:
for
loop.my_string = "Hello" for char in my_string: print(char)
Using enumerate() in for loops in Python:
enumerate()
to get both the index and value during iteration.for index, value in enumerate(my_list): print(index, value)
For loop vs while loop in Python:
for
and while
loops for different scenarios.# Using for loop for item in iterable: # Loop logic # Using while loop while condition: # Loop logic
Looping with break and continue in Python:
break
to exit and continue
to skip to the next iteration.for item in iterable: if condition: break # Exit the loop if another_condition: continue # Skip to the next iteration # Loop logic for valid iterations
Parallel iteration with zip() in for loops:
zip()
with a for
loop.names = ['Alice', 'Bob', 'Charlie'] ages = [25, 30, 35] for name, age in zip(names, ages): print(name, age)
Debugging techniques with for loop in Python:
print
statements, breakpoints, or other debugging tools to troubleshoot issues in a for
loop.for item in iterable: print(item) # Add print statements for debugging # Loop logic