Looping Through Tuples in Python: Iterating Over Tuple Elements

thumb_up 1  ·  sell Python tuple iteration, Looping through elements in Python tuples, Iterating over a Python tuple

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 1

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

Example 2

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

 
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

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back