![]() |
In this article, we will explore how to use a for loop to iterate through tuples in Python, along with some practical examples to illustrate its utility. Use For Loop to Iterate Tuple in PythonBelow are the ways by which we can use for loop to iterate Tuple in Python:
Using Simple For LoopIn the example, we created a tuple my_tuple containing five integers. We then used a for loop to iterate through each element of the tuple, and within the loop, we printed each element. Python3Output
1 2 3 4 5 Tuple of Tuple with For LoopHere, we have a tuple of tuples containing student names and their ages. The for loop unpacks each tuple into name and age variables, allowing us to print student information. Python3
Output
Alice is 23 years old. Bob is 20 years old. Charlie is 25 years old. Nested Tuples with For LoopThis example shows how to iterate through a tuple of tuples, where each inner tuple contains a student’s name and their scores. We calculate and print the average score for each student. Python3
Output
Alice's average score: 91.67 Bob's average score: 84.00 Charlie's average score: 89.67 Using enumerate functionThe enumerate function is useful when you want to access both the index and the value of each tuple element. Python3
Output
Index: 0, Value: 1 Index: 1, Value: 2 Index: 2, Value: 3 Index: 3, Value: 4 Index: 4, Value: 5 Loop through index numbersYou can also loop through the index numbers of a tuple and access the elements using indexing. Python3
Output
Index: 0, Value: 1 Index: 1, Value: 2 Index: 2, Value: 3 Index: 3, Value: 4 Index: 4, Value: 5 Loop through tuple elements in a rangeYou can loop through the elements of a tuple using a range and access them directly. Python3
Output
Value: 1 Value: 2 Value: 3 Value: 4 Value: 5 |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |