Level 1
0 / 100 XP

For In Loops

A for-in loop in Python is used to iterate over a sequence of elements. This can be a list, tuple, set, or any other iterable object. For each element in the sequence, the loop will execute the code block. Here is the syntax for a for-in loop in Python 3:

Python
# define a list of fruits fruits = ["apple", "banana", "cherry"] # iterate over the list of fruits for fruit in fruits: # print each fruit on a new line print(fruit)

In this example, we define a list of fruits and then use a for in loop to iterate over the list. The loop starts by setting the fruit variable to the first element in the list, which is "apple". It then prints the value of fruit and moves on to the next element in the list, setting the fruit variable to "banana". This process continues until all elements in the list have been processed.

Another useful feature of for in loops is that you can use the enumerate function to access both the index and the value of each element in the sequence. Here is an example:

Python
# define a list of fruits fruits = ["apple", "banana", "cherry"] # iterate over the list of fruits for index, fruit in enumerate(fruits): # print the index and the fruit on the same line print(index, fruit)

In this example, we use the enumerate function to access both the index and the value of each element in the list of fruits. The loop starts by setting the index variable to 0 and the fruit variable to "apple". It then prints both the index and the fruit on the same line. This process continues until all elements in the list have been processed.

I hope this lesson has been helpful in explaining how to use for in loops in Python 3. As always, practice makes perfect, so be sure to try out some for in loops on your own to get a better understanding of how they work.