Looping techniques<\/strong><\/p>\nThe list can also be used in iteration operation, for example:<\/p>\n
>>> for a in [ 4 , 6 , 9 , 2 ] : print a\r\n4\r\n6\r\n9\r\n2\r\n>>> for a in [ 4 , 6 , 9 , 2 ] : print a ,\r\n. . .\r\n4 6 9 2<\/pre>\nWhen looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate ( ) function.<\/p>\n
>>> for i ,v in enumerate ( [ ' tic ' , ' tac ' , ' toe ' ] ) :\r\n. . . print i, v\r\n0 tic\r\n1 tac\r\n2 toe<\/pre>\nTo loop over two or more sequences at the same time, the entries can be paired with the zip () function.<\/p>\n
>>> questions= [ ' namer , ' quest ' , ' favorite color ' ]\r\n>>> answers= [ ' lancelot ' , ' the holy grailblue ' ] \r\n>>> for q,a in zip ( questions , answers ) :\r\n. . . print 'What is your { 0 } ? It is { 1 }.'. format ( q , a) \r\nWhat is your name ? It is lancelot.\r\nWhat is your quest? It is the holy grail.\r\nWhat is your favorite color? It is blue.<\/pre>\nWhile 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.<\/p>\n
>>> words= [ ' cat ' , ' window ' , ' defenestrate ' ]\r\n>>> for w in words [ : ] :\r\n. . . if len ( w )>6:\r\n. . . words. insert ( 0 , w )\r\n>>> words\r\n[ ' defenestrate ' , ' cat ' , ' window ' , ' defenestrate ' ]<\/pre>\nNested list<\/strong><\/p>\nIt is possible to nest lists (create list containing other lists), for example:<\/p>\n
>>> q= [ 2 , 3 ]\r\n>>> p= [ 1 , q , 4 ]\r\n>>> len ( p )\r\n3\r\n>>> p [ 1 ]\r\n[ 2 , 3 ]\r\n>>> p [ 1 ] [ 0 ]\r\n2\r\n>>> p [ 1 ] . append ( ' xtra ' )\r\n>>> p\r\n[ 1 , [ 2 , 3 , ' xtra ' ] , 4 ]\r\n>>> q\r\n[ 2 , 3 , ' xtra ' ]<\/pre>\nNote 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.<\/p>\n
>>> id ( q )\r\n104386192\r\n>>> id (p [1] )\r\n104386192<\/pre>\n","protected":false},"excerpt":{"rendered":"In this Page, We are Providing Python Programming \u2013 Looping Techniques. Students can visit for more Detail and Explanation of Python Handwritten Notes\u00a0Pdf. Python Programming \u2013 Looping Techniques Looping techniques The list can also be used in iteration operation, for example: >>> for a in [ 4 , 6 , 9 , 2 ] : …<\/p>\n
Python Programming \u2013 Looping Techniques<\/span> Read More »<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[5],"tags":[],"yoast_head":"\nPython Programming \u2013 Looping Techniques - Python Programs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n