Tuple in Python
Tuple in Python
Topperworld.in
Tuples
❖ Forming a Tuple:
• All the objects-also known as "elements"-must be separated by a comma,
enclosed in parenthesis ().
• Although parentheses are not required, they are recommended.
• Any number of items, including those with various data types (dictionary,
string, float, list, etc.), can be contained in a tuple.
Example:
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Using square brackets we can get the values from tuples in Python.
©Topperworld
Python Programming
Example:
Output:
In the above methods, we use the positive index to access the value in
Python, and here we will use the negative index within [].
Example:
var = (1, 2, 3)
print("Value in Var[-1] = ", var[-1])
print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-3])
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
©Topperworld
Python Programming
❖ Tuples in a loop
Output:
(('Topper',),)
((('Topper',),),)
(((('Topper',),),),)
((((('Topper',),),),),)
(((((('Topper',),),),),),)
❖ Advantages of Tuples
• Tuples take less time than lists do.
• Due to tuples, the code is protected from accidental modifications. It is
desirable to store non-changing information in "tuples" instead of
"records" if a program expects it.
©Topperworld
Python Programming
©Topperworld