What is a tuple
Python One of the built-in data structures , Is an immutable sequence
The data type of tuple is tuple
Variable sequence and immutable sequence
* Immutable sequence : character string , tuple
* Immutable sequence : No increase , Delete , change , Operation of
* Variable sequence : list , Dictionaries
* Variable sequence : The sequence can be incremented , Delete , Change operation , The object address does not change
How tuples are created
Direct parentheses
a=('python','hello',90) # Parentheses can also be omitted a='python','hello',90
Use built-in functions tuple()
a=tuple(('python','hello',90))
Tuples containing only one element need parentheses and commas
a=(10,)
Empty tuple
a=() a2=tuple()
Tuple query operation
tup=(1,2,3,4,5) print(tup(0)) # The return value is 1 print(tup(1)) # The return value is 2
Why design tuples as immutable sequences
Once an immutable type object is created , All data inside the object cannot be modified
In a multitasking environment , There is no need to lock when operating objects at the same time
therefore , Try to use immutable sequences in the program
matters needing attention
* Tuples store references to objects
* If the object in the tuple itself is immutable , You can no longer reference other objects
* If the object in the tuple is a mutable object , The reference of the variable object cannot be changed , But the data can change
Tuples are not allowed to modify elements
because [20,30] Is list , The list is a variable sequence , All elements can be added to the list , The memory address of the list remains unchanged
Traversal of tuples
Tuples are iteratable objects , So you can use for...in Traverse
a=tuple(('python','hello','90')) for b in a: print(b)
summary
Technology