You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
my_tuple=3, 4.6, "dog"# Packingprint("Packed: my_tuple = ", my_tuple)
a, b, c=my_tuple# Unpackingprint(f"Unpacked: a = {a}, b = {b}, c = {c}")
# Packed: my_tuple = (3, 4.6, 'dog')# Unpacked: a = 3, b = 4.6, c = dog
Interating over tuples - for first_val, second_val in my_tuple_of_tuples
not_a_tuple= ("hello") # Only 1 element, so is a string literalparentheses_tuple= ("hello",) # Note the commano_parentheses_tuple="hello", # Parentheses are optionalprint("not_a_tuple's class = ", type(not_a_tuple))
print("parentheses_tuple's class = ", type(parentheses_tuple))
print("no_parentheses_tuple's class = ", type(no_parentheses_tuple))
# not_a_tuple's class = <class 'str'># parentheses_tuple's class = <class 'tuple'># no_parentheses_tuple's class = <class 'tuple'>
.count('value') - Return number of matching tuple items
.index('value') - Index of first matching tuple item
'arg'inmy_tuple - membership test
Named Tuples
Shorter than defining a class manually
Auto string repr
fromcollectionsimportnamedtupleCar=namedtuple('Car', 'color make mileage')
my_car=Car('red', 'Honda', 3812.4)
my_car.color# 'red'my_car.mileage# 3812.4# AutomaticString reprmy_car# Car(color='red', make='Honda', mileage=3812.4)# Like tuples, namedtuples are immutable:my_car.color='blue'# AttributeError: "can't set attribute"
Advantages of Tuple over List
Since tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:
We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes.
Since tuples are immutable, iterating through tuple is faster than with list. So there is a slight performance boost.
Tuples that contain immutable elements (and some Built-in functions) be used as a key for a dictionary. With lists, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.