Python Programming – Looping Techniques

In this Page, We are Providing Python Programming – Looping Techniques. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Python Programming – Looping Techniques

Looping techniques

The list can also be used in iteration operation, for example:

>>> for a in [ 4 , 6 , 9 , 2 ] : print a
4
6
9
2
>>> for a in [ 4 , 6 , 9 , 2 ] : print a ,
. . .
4 6 9 2

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate ( ) function.

>>> for i ,v in enumerate ( [ ' tic ' , ' tac ' , ' toe ' ] ) :
. . . print i, v
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip () function.

>>> questions= [ ' namer , ' quest ' , ' favorite color ' ]
>>> answers= [ ' lancelot ' , ' the holy grailblue ' ] 
>>> for q,a in zip ( questions , answers ) :
. . .   print 'What is your { 0 } ? It is { 1 }.'. format ( q , a) 
What is your name ? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

While iterating a mutable sequence, if there is a need to change the sequence (for example to duplicate certain items), it is recommended to make a copy of the sequence before starting iteration. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient.

>>> words= [ ' cat ' , ' window ' , ' defenestrate ' ]
>>> for w in words [ : ] :
. . . if len ( w )>6:
. . . words. insert ( 0 , w )
>>> words
[ ' defenestrate ' , ' cat ' , ' window ' , ' defenestrate ' ]

Nested list

It is possible to nest lists (create list containing other lists), for example:

>>> q= [ 2 , 3 ]
>>> p= [ 1 , q , 4 ]
>>> len ( p )
3
>>> p [ 1 ]
[ 2 , 3 ]
>>> p [ 1 ] [ 0 ]
2
>>> p [ 1 ] . append ( ' xtra ' )
>>> p
[ 1 , [ 2 , 3 , ' xtra ' ] , 4 ]
>>> q
[ 2 , 3 , ' xtra ' ]

Note that in the last example, p [ 1 ] and q refer to the same object, which can be cross-checked using the id ( ) built-in function.

>>> id ( q )
104386192
>>> id (p [1] )
104386192