For in Python: complete guide with 18 examples
The function for in python fundamental control structures. It is very useful for iterating over objects such as lists, tuples, dictionaries and sets, executing a block of code for each element in the sequence. With the for function, you can efficiently process sequences of data and perform operations on each element of a list, tuple, or dictionary. It is a powerful tool for object-oriented programming, allowing you to run reusable code for each element of a sequence.
We’ll explore Python’s for loop syntax , how to use the for() function, looping through lists, tuples, and dictionaries, nested loops, using break and continue, understanding lists with the for loop, and examples of using the for loop in Python . By the end of this article, you’ll be better equipped to use the for function in your next Python project, and better equipped to understand how to use this tool to make your code more efficient and readable.
Table of Contents
Basic for loop syntax
The basic Python for loop syntax lets you iterate over a sequence of elements, such as a list, tuple, set, or string. The for loop is extremely versatile and efficient for iteratively traversing elements in a data structure. The basic structure of the for loop in Python is as follows:
for element in sequence:
# do something with the element
Where “element” is a variable that assumes the value of each element of the sequence at each iteration. “sequence” represents the data structure that the for loop will iterate through.
Examples of using the for function in Python
Through the use of statements like else and break, it is also possible to add additional logic to the loop, making it even more flexible and powerful. Let’s look at some examples to better understand how the for loop works in Python:
Example 1: Iterating over a list
In this example, the for loop loops through each element of the list “fruits” and assigns the value of each element to the variable “fruit”. Next, we print the “fruit” variable to the screen.
fruits= ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
The output will be:
apple
banana
orange
Example 2: Iterating over a string
In this case, the for loop iterates over each character of the string “message” and prints each character to the screen.
message = "Hello, world!" for character in message:
print(character)
Example 3: Iterating over a numeric range
We use the range() function to generate a sequence of numbers. In this example, the for loop iterates over the numbers 1 through 5 and prints each number to the screen.
for i in range(1, 6): print(i)
After the normal Python for loop finishes, when all iterations are done, we execute the else statement. This example prints the numbers 0 through 4 and then prints the message “Loop complete!”. Look:
for i in range(5):
print(i)
else:
print("Tie completed!")
The “break” instruction is an efficient way to avoid unnecessary iterations in situations where we modify the iteration exit condition at some point in the loop. In this example, the for loop loops through the list “fruits” and prints each element until we find the word “banana”. At this point, we break the loop. Look:
frutas = ['apple', 'banana', 'orange']
for fruit in fruits:
if fruit == 'banana':
break
print(fruit)
Using the range() function in a for loop
The range() function in Python is a convenient way to generate a sequence of numbers in a for loop.
The basic syntax of the range() function is range(start, stop, step), where “start” is the starting number of the sequence, “stop” is the ending number (not included) and “step” is the increment between the numbers of the sequence.
For example, if we want to iterate over the numbers 1 to 10 with an increment of 2, we can use the range(1, 10, 2) function. Let’s look at an example in which the for loop iterates over the sequence generated by the range(1, 10, 2) function and prints each number to the screen:
for i in range(1, 10, 2):
print(i)
The output will be:
1
3
5
7
9
We can omit the value of “start” by using only the “stop” argument in the range() function. In this case, the value of “start” is being considered as 0 by default. For example, range(5) generates the sequence of numbers from 0 to 4. If we omit the value of “step”, the increment is assumed to be 1. For example, range(1, 5) generates the sequence of numbers from 1 to 4.
In other words, the range() function plays a key role when working with for loops in Python. In addition, it offers a more practical and efficient approach to generating numerical sequences. With the range() function, we can define the start, end and step of the sequence, allowing precise control over the iterations of the loop. In this way, this function becomes a powerful ally to traverse a specific range of values in a simplified and optimized way. We can combine the range() function with other control structures, such as conditionals, to create custom iterations and perform specific tasks for each element of the generated sequence.
For function in python with lists, tuples and dictionaries
The for loop in Python is especially useful when used with data structures like lists, tuples, and dictionaries. It allows you to go through the elements of these structures and perform some action for each element. Let’s explore how we can use the for loop in each of these situations:
The for loop in Python is especially useful when used with data structures like lists, tuples, and dictionaries. It allows you to go through the elements of these structures and perform some action for each element. Let’s explore how we can use the for loop in each of these situations:
For loop with lists:
Lists are data structures that can store multiple elements in a single variable. We can iterate through the elements of a python list using the for loop, as exemplified in this example. The for loop iterates over each element of the list “fruits” and, at each iteration, we assign the value of the element to the variable “fruit”. Next, we print the value of the “fruit” variable on the screen.
frutas = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
The output will be:
apple
banana
orange
For loop with tuples:
A tuple is a list-like data structure.
The for loop is a control structure that can be used to iterate over the elements of a collection of objects, such as lists, tuples, or sets. In our example, we are using the for loop to iterate over the elements of the “coordinates” tuple and, with each iteration, assign the value of the element to the “coordinate” variable.
A constant is a variable that cannot change its value after it is created. It keeps the same value permanently and cannot be modified. In other words, once created, the constant remains unchanged.
coordinates = (10, 20, 30)
for coordinate in coordinates:
print(coordinate)
The output will be:
10
20
30
for loop with dictionaries:
Dictionaries are data structures that allow you to store and retrieve information using key-value pairs. We can loop through the elements of a dictionary using the for loop, as exemplified here. We use the items() method to get a list of key-value pairs from the “person” dictionary. The for loop iterates over each key-value pair, and at each iteration we assign the key value to the “key” variable and the corresponding value to the “value” variable. We then print the “key” and “value” values to the screen.
person = {'name': 'John', 'age': 25, 'city': 'São Paulo'}
for key, value in person.items():
print(key, value)
The output will be:
name John
age 25
city São Paulo
The for loop is a powerful tool for iterating over the elements of lists, tuples, and dictionaries in Python. With this functionality, we can conveniently and efficiently access and manipulate the elements of these structures.
Nested for function in python
The nested for loop (or “zero-length nested for”) is a feature of Python that allows you to run a block of code without a specific loop, using just a for statement.
Suppose you want to check whether a number is prime using a nested for loop. You can do this as shown in this example. The variable ia is incremented each iteration of the loop. However, the loop exits when the number is divisible by the value of i.
number = 17
for i in range(2, number):
if number % i == 0:
break
print("The number", number, "is cousin.")
If you want to run the same block of code without using a loop, you can do that using the for statement without an argument. Therefore, we will create an empty loop in which while, no further actions will be performed, but the code block inside the loop will be executed only once:
number = 17
for i in ():
if number % i == 0:
break
print("The number", number, "is cousin.")
In short, the nested for loop in Python is a powerful feature that lets you execute a block of code efficiently and concisely without the need for a specific loop. This functionality offers flexibility and simplicity when dealing with complex iteration tasks in Python.
Using the break and continue statement in a for loop
We commonly use break and continue statements in for loops in Python to control loop behavior.
Break
We use the break statement to exit a for loop before it terminates normally. When we execute the break statement, we break the loop and the program continues its execution after the loop. For example, the for loop iterates from 0 to 9, but when i equals 5, we execute the break statement and break the loop. We ignore values of i that are odd:
for i in range(10):
if i == 5:
break
print(i)
Continue
We use the continue statement to skip a step in a for loop and continue with the next iterator. When we execute the continue statement, the for loop ignores the current value of i and advances to the next iterator. For example, the for loop iterates from 0 to 9, but when i is an even number, we execute the continue statement and ignore the value of i. We only print the values of i that are odd:
for i in range(10):
if i % 2 == 0:
continue
print(i)
In Python, the use of loops is common and in certain cases, it is necessary to use break and continue statements to control the behavior of the loop. We use the break statement to break the loop before it ends normally. On the other hand, we use the continue statement to skip a step in the loop and continue with the next iterator.
List comprehension with for function in python
List comprehension is a concise way to create a list from an existing list or other iterable sequence. It is created using the [expression for each element of the sequence] syntax, where the expression is executed for each element of the sequence and the result is added to the list.
For example, if you want to create a list of even numbers from the sequence of numbers 0 to 9, you can use list comprehension. In this example, we run the expression i for i in range(10) if i % 2 == 0 for each element of the sequence range(10), and add the even numbers to the list.
pair_numbers = [i for i in range(10) if i % 2 == 0]
We use Python list comprehension to create more complex lists. We can combine list comprehension with the filter function to create more complex lists from existing data. List comprehension is a concise way of working with lists in Python. In this example, we use the filter function to filter only even numbers from the list generated by the for loop. We use the lambda lambda function x: x % 2 == 0 to check whether each element is even or odd.
pair_number = list(filter(lambda x: x % 2 == 0, range(10)))
List comprehension is a concise way to create a list from an existing list or other iterable sequence. The list comprehension function is a powerful way to work with lists in Python. We can combine it with other functions like filter to create more complex lists from existing data.
while loop vs. for loop in python
You can use a for loop in Python to loop through a list of specific numbers or values. For example we have this code will print the numbers 0 to 4:
for i in range(5):
print(i)
The while loop is an important control structure in programming, as it allows you to iterate over a list indefinitely while satisfying a specific condition, regardless of the length of the list. For example, here in this code, we have the numbers 0 to 9 printed:
i = 0
while i < 10:
print(i)
i += 1
We use the for loop to iterate over an array or sequence of known values, while we use the while to execute a task in an unknown number of iterations, checking a condition in each iteration.
Recommendations for using the for function in Python
Here are some recommendations for using the for loop in Python:
1- Use the for loop when you need to iterate over an array of numbers or specific values. The for loop allows you to specify the start and end of the track, which can make your code more layman and maintainable.
2- Use the for loop when you need to do operations with each value in the range.
3- Use the for loop when you need to do operations with each value in the range and save the result to a new variable.
4- Use the for loop when you need to do operations with each value in the range and save the result to a new file.
5- Use the for loop when you need to do operations with each value in the range and save the result to a new database.
CONCLUSION
The for function in Python is a powerful and versatile tool for solving problems involving iteration over sequences of data, such as lists, tuples and strings. With the for function, it is possible to perform unidirectional, bidirectional and negative indices iterations, in addition to controlling the iteration output condition.
By learning and practicing using the for function, you can become more efficient and effective in your work with Python programming, solving problems faster and more elegantly.
Always remember that practice is key to understanding and applying Python functions and features. As such, we strongly recommend that you experiment with different situations and exercises with the for function. Therefore, this will allow you to gain even more familiarity, confidence and skill in using this tool.
Ultimately, therefore, it is crucial not to forget to look for additional resources to constantly improve your knowledge of Python programming. Furthermore, it is highly recommended to explore a variety of resources such as tutorials, books and programming communities in order to broaden your expertise in the language. With dedication and practice, you’ll be ready to tackle the most complex Python programming challenges. Besides the ‘for’ function, another important function in Python is the ‘len’ function.