Pages

Thursday, February 18, 2021

For loop in Python

For loop

For loops are used when a block of code needs be executed over a range or list of values. 

List of values can be a List, Tuple, Set, Dictionary or String. 

Number of times the loop is repeated is based on the number of values present in an iterable. 

Syntax:

for element in iterable

iterable refers to a range, list, tuple, set, dictionary or string. 

element refers to the element from the iterable and can be accessed in the loop using this name. 

Range

Let's have a look at a simple example of for loop over a range of numbers. 

For loop in Python over a range

In the above example, for loop is repeated 10 times (from 0 to 9) and for every occurrence number will hold the corresponding value through out the loop (i.e., on the first iteration 'number' will hold the value of '0', on second iteration 'number' will hold the value of '1'...). 

List

Let's have a look at another simple example of for loop over a list. 

For loop in Python over a list

In this example, for loop is repeated for each element in the list (new_list) and corresponding value of the element can be accessed by using 'list_element' through out the loop. 

We are able to access the elements from a list directly. There is one other way of using for loop on a list is by using range.

For loops in Python - List & Range

In the above example, Instead of repeating the for every element in the loop, we are repeating the loop on the index (by calculating the length of a list).
  • 'len' function would return the length of the list. 
  • 'index' represents the index of the list for every iteration. 
  • Elements of a list can be accessed by using index (new_list[index]).
Result of this example is same as the previous. But, this becomes helpful we are to consider index for the operation inside the loop. 

For loop over a tuple is same as list. 

Set

Let's have a look at an example of for loop over a set. Unlike List and Tuple, Set is an unordered collection of data. Data is stored in no specific order and cannot be accessed by index. 

For loop in Python over a Set

Just like for loop over a range and list, for loop is repeated for all the elements in a set. Because of the way data is stored in a set, Data returned could be in any order and the result could vary every time the program is run. 

Dictionary

Dictionary is different from other iterables due to the way data is stored (key and value combination). 

For loop on a dictionary would only return it's key. 

For loop in Python over dictionary

In the above example, for loop is repeated for every key in the dictionary and data in the dictionary can be accessed by using corresponding key. 

for loop in Python over a dictionary

String

Just like other lists, Strings are also iterable objects in Python and for loop can be used in the same way on strings as well. 

For loop in Python over a string

For strings, each character would be considered as a separate element and for loop is repeated for all the characters in the string passed. 

Nested For loops

Nested for loops can be used if we have an iterable inside another iterable. E.g.: List inside a list or String inside a List.

Let's have a look at an example using the List. 

Nested For loops in Python

In the above example,
  • Line - 2: 'new_list' is created with list of strings.
  • Line - 5: for loop is repeated for every string in the list. 
  • Line - 7: for loop is repeated for every character for every list element (string).

break statement

In all the examples we have seen, for loop is executed for all the elements in the iterable. This doesn't necessarily needed always, we can use break statement. 

Whenever break statement is executed, loop will be terminated and no further statements would be executed.

break statement in Python

In the above example, for loop is repeater over a range of 10, once the number is '5', loop will be terminated. 

continue statement

break statement would terminate the entire loop. Where as continue statement would only terminate the current iteration and continues the loop from the next iteration.

continue statement in Python

In the above example, print statement won't be executed for number '5'.

pass statement

pass statement works like a place holder if no specific operations is required and is mandatory by syntax. 

pass statement in Python

In the above example, 'pass' statement would work as a place holder to avoid any error. 

Else 

Else in for loop isn't exactly same as if-else. Instead this is executed once the for loop is completed. 

One thing to remember here is 'else' part would only be executed if the for loop is executed completely and not terminated by using 'break' statement. If break statement is executed, else part wouldn't be executed as well.

Else in for loop in Python

In the above example, else is executed once for loop is completed (after all the elements in the list).

Hope the above was a bit of help to understand the for loops in Python. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

2 comments:

  1. Nice one. You can add nested if example too.

    ReplyDelete
    Replies
    1. Thanks, I will add the examples for if condition on a different post.

      Delete

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...