Python for Loop

A loop is a fundamental programming idea that is commonly used in writing computer programs. It is a sequence of instructions that is repeated until a certain condition is reached. A for loop has two sections: a header specifying the iterating conditions, and a body which is executed once per iteration . The header often declares an explicit loop counter or loop variable, which allows the body to know which iteration is being executed.
How to Python for loop
for item in sequence: statements(s)

Using for loop in Python List

directions = ['North','East','West','South'] for pole in directions: print(pole)
North East West South
Here directions is a sequence contains a list of directions. When the for loop executed the first item (i.e. North) is assigned to the variable "pole". After this, the print statement will execute and the process will continue until we rich the end of the list.

Using for loop in Python Tuple

colors = ("Red", "Blue", "Green") for color in colors: print(color)
Red Blue Green

Using for loop in Python Dictionary

myDict = dict() myDict["High"] = 100 myDict["Medium"] = 50 myDict["Low"] = 0 for var in myDict: print("%s %d" %(var, myDict[var]))
High 100 Medium 50 Low 0

Using for loop in Python String

str = ("Python") for c in str: print(c)
P y t h o n

Python for loop range() function

How to PYthon range function in for loop
The range function in for loop is actually a very powerful mechanism when it comes to creating sequences of integers. It can take one, two, or three parameters. It returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound , possibly in increments (steps) of some other number (one, by default). Note for Python 3 users: There are no separate range and xrange() functions in Python 3, there is just range, which follows the design of Python 2's xrange.
  1. range(stop)
  2. range(start,stop)
  3. range(start,stop,step)
It is important to note that all parameters must be integers and can be positive or negative .

Python range() function with one parameters

  1. stop: Generate numbers up to, but not including this number.
for n in range(4): print(n)
0 1 2 3

It can be thought of working like this:

i = 0 print i i = 1 print i i = 2 print i i = 3 print i

So you can see that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.

Python range() function with two parameters

  1. start: Starting number of the sequence.
  2. stop: Generate numbers up to, but not including this number.
for n in range(5,10): print(n)
5 6 7 8 9
The range(start,stop) generates a sequence with numbers start, start + 1, ..., stop - 1. The last number is not included.

Python range() function with three parameters

  1. start: Starting number of the sequence.
  2. stop: Generate numbers up to, but not including this number.
  3. step: Difference between each number in the sequence.
for n in range(0,10,3): print(n)
0 3 6 9

Here the start value is 0 and end values is 10 and step is 3. This means that the loop start from 0 and end at 10 and the increment value is 3.

Python Range() function can define an empty sequence, like range(-10) or range(10, 4). In this case the for-block won't be executed: example
for i in range(-10): print('Python range()')

The above code won't be executed.

Also, you can use Python range() for repeat some action several times: example
for i in range(2 ** 2): print('Python range()!!')
Python range()!! Python range()!! Python range()!! Python range()!!

Decrementing for loops

If you want a decrementing for loops , you need to give the range a -1 step example
for i in range(5,0,-1): print (i)
5 4 3 2 1

Accessing the index in 'for' loops in Python

python for loop index
Python's built-in enumerate function allows developers to loop over a list and retrieve both the index and the value of each item in the containing list. It reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable that yields a two-item tuple of the index and the item that the original iterable would provide. example
months = ["January", "February", "March", "April", "May", "June", "July","August", "Spetember", "October", "November", "December"] for idx, mName in enumerate(months, start=1): print("Months {}: {}".format(idx, mName))
Months 1: January Months 2: February Months 3: March Months 4: April Months 5: May Months 6: June Months 7: July Months 8: August Months 9: Spetember Months 10: October Months 11: November Months 12: December

Note: the start=1 option to enumerate here is optional. If we didn't specify this, we'd start counting at 0 by default.

Python enumerate function perform an iterable where each element is a tuple that contains the index of the item and the original item value.

So, this function is meant for:

  1. Accessing each item in a list (or another iterable).
  2. Also getting the index of each item accessed.

Iterate over two lists simultaneously

In the following Python program we're looping over two lists at the same time using indexes to look up corresponding elements.

grades = ["High", "Medium", "Low"] values = [0.75, 0.50, 0.25] for i, grade in enumerate(grades): value = values[i] print("{}% {}".format(value * 100, grade))
75.0% High 50.0% Medium 25.0% Low

Using Python zip() in for loop

The Python zip() function takes multiple lists and returns an iterable that provides a tuple of the corresponding elements of each list as we loop over it.
grades = ["High", "Medium", "Low"] values = [0.75, 0.50, 0.25] for grade, value in zip(grades, values): print("{}% {}".format(value * 100, grade))
75.0% High 50.0% Medium 25.0% Low

Nested for loop in Python

Python nested for loop
for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
for outer in range(1,5): for nested in range(1,5): res = outer*nested print (res, end=' ') print()
1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16
Here the Python program first encounters the outer loop, executing its first iteration. This first iteration triggers the nested loop, which then runs to completion. Then the program returns back to the outer loop, completing the second iteration and again triggering the nested loop. Again, the nested loop runs to completion, and the program returns back to the top of the outer loop until the sequence is complete or a break or other statement disrupts the process. The print() function inner loop has second parameter end=' ' which appends a space instead of default newline. Hence, the numbers will appear in one row.

Using else statement in python for loop

Unlike other popular programming languages, Python also allows developers to use the else condition with for loops. example
lst = [1,2,3,4,8] for num in lst: if num >5: print ("list contains numbers greater than 5") break else: print("list contains numbers less than 5");
list contains numbers greater than 5
In the above example, there is list with integer number. While entering the for loop each number is checked with greater than 5 or not. Here you can see the else executes only if break is NEVER reached and loop terminated after all iterations.