-> A tuple in Python is a built-in collection data type used to store multiple items in a single variable.
-> It is characterised by being ordered, immutable (unchangeable), and allowing duplicate values
-> Similar to List
-> Insertion Order is maintained
-> Duplicate elements are allowed
-> Performance - Tuple is good
t = (10,20,30,40,50)
t2 = ()
print(type(t2))
t3 = (10)
print(type(t3))
t4 = (10,)
print(type(t4))
Output:
t1 = (10,20,30)
t2 = (40,50,60)
t3 = t1 + t2
print(t3)
print(t1*2)
print(100 in t1)
print(100 not in t1)
Output:
(10, 20, 30, 40, 50, 60)
(10, 20, 30, 10, 20, 30)
False
True
Tuple Comprehension:
numbers = (no for no in range(1,11))
print(numbers) #generator object
Output:
at 0x000001D88B691A80>
Packing and Unpacking:
t = 10,20,30
print(type(t))
no1, no2, no3 = t
print(no1)
print(no2)
print(no3)
Output:
10
20
30
eval():
-> The eval() function in Python is a built-in tool that dynamically parses, compiles, and evaluates a string as a Python expression.
t = eval(input("Enter tuple elements: "))
print(t)
total = 0
for num in t:
total+=num
print(total)
Output:
Enter tuple elements: 10,20,30,50
(10, 20, 30, 50)
110
*Performance: *
import sys
l = [10,20,30]
t = (10,20,30)
print(sys.getsizeof(l)) #Dynamic Sizing -> Mutability
print(sys.getsizeof(t))
Output:
88
64
Top comments (0)