NEPTUNIAN ANALYTICS

For Loop

A for loop is used to traverse a sequence. For example, you can use a for loop to traverse a list. To create a for loop you use the for keyword. The syntax for a for loop is shown below.

for i in item_to_be_traversed:
   #do this

In a for loop, the code to be performed must be indented as shown above.

We can use a for loop to print the items of our shopping list one by one.

Printing the contents of the shopping list

for i in shopping_list:
   print(i)

Output

strawberry
apple
pear
bread

By iterating through the list, we printed each item of the list. Now, you may be wondering what is so different about doing this compared to calling print on shopping_list. So let’s see shall we.

Calling print on the shopping_list

To print the shopping_list enter the below code into a code editor:

print(shopping_list)

Output

[‘strawberry’, ‘apple’, ‘pear’, ‘bread’]

By calling print on the shopping_list we printed the list as a whole. Whereas using a for loop prints each list item sequentially. Being able to access each individual element of a list is often an important task in programming. If, for example, you had a task where you needed to perform an operation on each item of a list.

Try creating your own for loops. For example, create a for loop to traverse a new list you created.