oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

    Python - Loop Tuples


    Loop Through Tuple Items

    You can traverse the items in a tuple with Python's for loop construct. The traversal can be done, using tuple as an iterator or with the help of index.

    Syntax

    Python tuple gives an iterator object. To iterate a tuple, use the for statement as follows −

    for obj in tuple:
       . . .
       . . .
    

    Example

    The following example shows a simple Python for loop construct −

    tup1 = (25, 12, 10, -21, 10, 100)
    for num in tup1:
       print (num, end = ' ')
    

    It will produce the following output

    25 12 10 -21 10 100
    

    Loop Through Tuple Items using Index

    To iterate through the items in a tuple, obtain the range object of integers "0" to "len-1".

    Example

    tup1 = (25, 12, 10, -21, 10, 100)
    indices = range(len(tup1))
    for i in indices:
       print ("tup1[{}]: ".format(i), tup1[i])
    

    It will produce the following output

    tup1[0]: 25
    tup1 [1]: 12
    tup1 [2]: 10
    tup1 [3]: -21
    tup1 [4]: 10
    tup1 [5]: 100