Skip to main content

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.

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

Post a Comment

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i