Sequence is a commonly used data storage method in programming. almost every programming language provides a table data structure, such as one-dimensional and multi-dimensional arrays in C and Basic. The sequence types provided by Python are the most abundant, flexible, and powerful in all programming languages. Sequence is a commonly used data storage method in programming. almost every programming language provides a table data structure, such as one-dimensional and multi-dimensional arrays in C and Basic. The sequence types provided by Python are the most abundant, flexible, and powerful in all programming languages.
A sequence is a series of continuous values, which are usually related and arranged in a certain order. Commonly used sequence structures in Python include lists and tuples.
Tuples are similar to lists, but they belong to an unchangeable sequence. Once a tuples are created, they cannot be modified in any way.
The tuples are defined in the same way as the list, but all elements are placed in a pair of parentheses ("" and ")" instead of square brackets.
Create and delete tuples
Use "=" to assign a tuple to a variable
>>> A_tuple = ('A ',)
>>> A_tuple
('A ',)
>>> A_tuple = ('A', 'B', 'mpilgrim', 'z', 'example ')
>>> A_tuple
('A', 'B', 'mpilgrim', 'z', 'example ')
>>> A = 3
>>>
3
>>> A = 3,
>>>
(3 ,)
Use the tuple function to convert other sequences into tuples.
>>> Print tuple ('abcdefg ')
('A', 'B', 'C', 'D', 'e', 'e', 'F', 'g ')
>>> AList
[-1,-4, 6, 7.5,-2.3, 9,-11]
>>> Tuple (aList)
(-1,-4, 6, 7.5,-2.3, 9,-11)
You can use del to delete tuples. you cannot delete tuples.
Difference between tuples and lists
Once defined, the data in the tuples cannot be changed.
Tuples do not have methods such as append (), extend (), and insert (), and cannot be added to tuples;
Tuples do not have the remove () or pop () method, nor can they perform del operations on the elements of the tuples. elements cannot be deleted from the tuples.
The built-in tuple () function accepts a list parameter and returns a tuple containing the same element, while the list () function accepts a tuple parameter and returns a list. In effect, tuple () freezes the list, while list () melts the tuples.
Advantages of tuples
The speed of tuples is faster than that of the list. If a series of constant values are defined and only traversal is required, tuples are generally used instead of lists.
Writing protection for data that does not need to be changed will make the code more secure.
Some tuples can be used as dictionary keys (especially those containing immutable data such as strings, values, and other tuples ). The list can never be used as a dictionary key, because the list is not immutable.
The above is a detailed explanation of the sequence structure of tuples in the Python language and the details of the instance. For more information, see other related articles in the first PHP community!