Python For Loop

Python for Loop

Python For Loop – In programming, to repeat an action, loops are used. In Python programming for loop is used to iterate the sequences. In Python, sequences are like String, tuple lists etc. In this article, we will explore the for loop use cases with the interesting examples. This article contains the following topics.

  • for loop with xrange()
  • for loop with Sequences
  • List comprehension
  • Reading the file
  • Nested for loop

Python For Loop – for loop with xrange()

Syntax of for loop.

for <variable> in xrange(<an integer expression>):

<Statement 1>

<Statement 2>

We generally use xrange with for loop. Let us see how we can use xrange with for loop.

If we use expression xrange as shown below. The xrange() gives you nothing.

>>> xrange(10)

xrange(10)

>>> print xrange(10)

xrange(10)

>>>

The xrange returns the xrange object. The xrange creates the values when asked for them.

We use for loop to retrieve the values from xrange. In Python 3.x xrange keyword is denoted by range.

Let us see the example of for loop with xrange().

for each in xrange(1,5):

print each

The above syntax tells, start from 1 and ends before 5. Let us see the output.

Output.

1

2

3

4

The above output is vertical. If you want to print horizontal then use “,” as shown in next example.

for each in xrange(1,5):

print each,

Output.

1 2 3 4

Python For Loop – for loop with Sequences

Let us another syntax of for loop which is used with sequences

for <variable> in <sequence>:

<Statement 1>

<Statement 2>

In Python strings, tuples lists are the sequences.

Let us use the Python for loop with strings, tuples, and lists.

With String:

Let us see how to iterate over the string.

str1 = “What we think we become”

for each in str1:

print each,

Output.

W h a t   w e   t h i n k   w e   b e c o m e

Python For Loop – With Tuple:

See the simple to iterate over the tuple.

tuple1 = (1,2,4,5,89,90,56)

for each in tuple1:

print each,

Output.

1 2 4 5 89 90 56

The iteration of the tuple and list is the same. Let us take a complex example. Now we will how to iterate over the list which contains tuples.

list1 = [(“a”,1),(‘b’,3),(‘c’,2),(‘d’,5),(‘e’,6)]

for k,v in list1:

print k,” : “,v

In the above code, I used tuple pairs. Let us see the output then discuss the for loop.

Output.

a  :  1

b  :  3

c  :  2

d  :  5

e  :  6

Here the variables ‘k’and ‘v’ are used to unpack the tuple pair. Let us take a less complex example of the above code.

list1 = [(“a”,1),(‘b’,3),(‘c’,2),(‘d’,5),(‘e’,6)]

for each in list1:

k,v = each

print k,” : “,v

The output of the above code is the same. So, ‘k’and ‘v’ unpack the tuples, are being referred by the variable each.

Note: If you are sure, all tuples contain 2 values then you can use the above code.

Python Online Training

List comprehension

List comprehension is the concise way to create a list. Sometimes it is called as one-liner code.

Let us learn by the examples.

Find the Square of numbers of the list.

list1 = [1,2,3,14,5,78,]

list2 = []

for each in list1:

list2.append(each**2)

print list2

Let us see the output of the above code.

Output.

[1, 4, 9, 196, 25, 6084]

You can see to find the square of the number we used 4 lines.

The same thing can be archived in one line using the list comprehension.

list1 = [1,2,3,14,5,78,]

print [each**2 for each in list1]

Let us see more example of list comprehension.

Find the square of number of greater than 3.

list1 = [ 1 , 2 ,3 ,14 ,5 ,78]

print [each**2 for each in list1 if each > 3]

Let see the output of the code.

Output.

[196, 25, 6084]

Flattening Python lists by for loop

Consider you have a list like [[ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] and you want to make list flat, like [ 1, 2, 3, 4, 5, 6].

See the example below.

list1 = [[ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]

print [ e for sublist in list1 for e in sublist ]

Let us see the output.

[1, 2, 3, 4, 5, 6]

In above example, you can see that two for loops are there, one for loop for the outer list and one for loop for inner lists. Printing value is e. If you still have doubt look next example.

>>> list2 = [ [ [ 1, 2 ], [ 3, 4 ] ], [ [ 5, 6 ], [ 7, 8 ] ] ]
>>> [e for sublist1 in list2 for sublist2 in sublist1 for e in sublist2]
[1, 2, 3, 4, 5, 6, 7, 8]

In above example three lists are there, therefore we used three for loops.

Reading a file line by line.

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to a simple code.

See the  txt file below.
Differences

Let us see the sample code.

file_obj = open(“file1.txt”,’r’)

for line in file_obj:

print line

file_obj.close()

output
Differences

The output is very clear.

Python For Loop – Nested loop.

A nested loop is a loop within a loop, an inner loop within the body of an outer one. Consider inner loop runs m times and outer loop run n times than the total maximum iteration of the inner loop can be n*m.

Let us see the code of sorting.

list1 = [1, 9, 8, 0, 3, 7, 4, 2]

for i in xrange(len( list1 ) – 1 ):

for j in xrange( i+1 , len(list1)):

if list1[i] > list1[j]:

list1[i] , list1[j] = list1[j] , list1[i]

print list1

In the above code, you can easily see one is outer loop and second is the inner loop. The value of the outer loop has been compared with all next values by the inner loop. If the value of the outer loop is bigger than the compared value then the values get swapped.

Let us see the output.

Output:

[0, 1, 2, 3, 4, 7, 8, 9]

I hope you enjoyed the articles.

Leave a reply:

Your email address will not be published.

Site Footer

Not found