Tools, FAQ, Tutorials:
'for ... in' Statement with List of Tuples
How to use "for ... in" statements with a list of tuples in Python code?
✍: FYIcenter.com
Usually, "for ... in" statements are used with simple lists.
But you can also use a "for ... in" statement with a list of tuples.
In this case, you can put multiple looping variables inside the loop item:
for (v1, v2, ... ) in list_of_tuples:
statement-block
else :
statement-block
For example:
>>> for (v1, v2) in [('gallahad','the pure'), ('robin', 'the brave')]:
... print(v1+", "+v2)
...
gallahad, the pure
robin, the brave
This form of loops is very useful if you want to loop through a "dict" object:
>>> d = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for (k,v) in d.items():
... print(k+": "+v)
...
gallahad: the pure
robin: the brave
And it is also very useful if you want to loop through a "list" object:
>>> l = ['tic', 'tac', 'toe'] >>> for (i,v) in enumerate(l): ... print(i, v) ... 0 tic 1 tac 2 toe
⇒ 'while ... else' Repeating Statement Blocks
⇐ 'for ... in ... else' Repeating Statement Blocks
2018-08-14, ∼2252🔥, 0💬
Popular Posts:
How to use the built-in "context" object in Policy expressions? The built-in "context" object can be...
Where to find tutorials on OpenID? Here is a large collection of tutorials to answer many frequently...
How to create a navigation file like navigation.xhtml for an EPUB 3.0 book? At least one navigation ...
How to use the XML to JSON Conversion Tool at freeformatter.com? If you want to try the XML to JSON ...
How to add an API to an API product for internal testing on the Publisher Portal of an Azure API Man...