3.4.1. Tuples - JulTob/Python GitHub Wiki
π Tuples
Immutable lists. Static arrays.
A tuple is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries.
Syntactically, a tuple is a comma-separated list of values:
t = 'a', 'b', 'c', 'd', 'e'
Parentheses may be used
Tpl = ('a','b','c','d','e')
print ( Tpl )
print ( Tpl[1] )
print ( Tpl[1:3] )
print(Tpl.index('a'))
You cannot change the values of a Tuple.
Empty_tuple = tuple()
one_value_tpl = ( 4,); # With the comma and semicoma
Alert= ("Tornado", "Radiation", "Zombies")
for a in Alert:
print(a)
if "Zombies" in Alert: # containment in tuple
print("Oh, F*ck")
how_many_alerts = len(Alert)
position = Alert.index("Radiation")
del Alarm # Alarm tuple deleted
fruit = tuple(( "banana", "banana", "banana" ))
# Constructed, use Double parentesys
fruit.count("banana")
print(sorted(fruit))
Packing & Unpacking
Person = (βJaneβ,βDoeβ,21,'Female')
(Name,Surname,Age,Gender) = Person
my_list = list(Tpl) # Converts tp list
tpl2 = tuple(my_list) #Converts to tuple
min(Tpl)
max(Tpl)
>>> t = tuple('lupins')
>>> print(t)
('l', 'u', 'p', 'i', 'n', 's')
π» Empty tuple
t = tuple()
π Tuple from a sequence
>>> t = tuple('lupins')
>>> print(t)
('l', 'u', 'p', 'i', 'n', 's')
ππΌ Indexing
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print(t[0])
'a'
>>> print(t[1:3])
('b', 'c')
You can't modify the elements of a tuple, but you can replace one tuple with another:
>>> t = ('A',) + t[1:]
>>> print(t)
('A', 'b', 'c', 'd', 'e')