Tuples are a sequence of values, can be of any type, can be indexed by subscript, but tuples are immutable
To create a tuple:
t= (' A ', ' B ', ' C ')
T= ' A ',----only one element needs to be appended with a comma
Tuple ()---parameter can be a sequence (string, list, tuple)
T=tuple (' hello ')----results (' h ', ' e ', ' l ', ' l ', ' o ')
Get element:
T[0] T[1:3]
To modify a tuple:
T=tuple (' Hello ')
t= (' H ',) +t[1:]---can replace an entire tuple cannot modify elements of a tuple
Tuple Exchange Assignment:
A,b=b,a
Tuples as return values:
def min_max (t):
return Max (t), min (t)
T= (1,3,2,5)
Print (Min_max (t))
Variable-length parameter tuples---functions can receive an indefinite number of parameters:
Collect----
def printall (*args):---parameter names that begin with a * collect all parameters on a single tuple
Print (args)
Printall (1,2.0, ' H ')
Disperse---
T= (7,3)
Print (Divmod (*t))-----Divmod () returns a tuple (quotient, remainder); *t groups The tuples
List and tuples, dictionaries, and tuples:
ZIP---sequence variable tuple table
s= ' abc '
t=[0,1,2]
L=list (Zip (s,t))-----[(' A ', 0), (' B ', 1), (' C ', 2)]
D=dict (Zip (s,t))----{' A ': 0, ' B ': 1, ' C ': 2}
Dictionary conversion to tuples:
D={' A ': 0, ' B ': 1, ' C ': 2}
For Key,val in D.items ():
Print (Key,val)
Results:
A 0
B 1
C 2
Compare tuples:
The relational operator is available for tuples and other sequences, and Python starts from the first element of each sequence, and if equal compares the next element until a different element is found
x= (1,2,4)
Y= (a)
Print (x>y)----true
Print (x<y)----false
Sorting---sort () for list
T.sort (reverse=true)---descending order
Tuple--python