Python Tuple operation details

  • 2020-04-02 13:27:50
  • OfStack

Create tuples

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

Create an empty tuple
tup1 = ();

When there is only one element in a tuple, a comma is added after the element to disambiguate it
tup1 = (50,);

Tuples are similar to strings, subscript index from 0, can be intercepted, combination, and so on.
Access tuples
Tuples can use subscript indexes to access values in tuples, as in the following example:
#!/usr/bin/python
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
# Output results of the above examples: 
#tup1[0]:  physics
#tup2[1:5]:  [2, 3, 4, 5]

Modify tuples
The values of elements in tuples are not allowed to be modified, but we can join and combine tuples, as shown in the following example:
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
#  The following modification of a tuple element operation is illegal. 
# tup1[0] = 100;
#  Create a new tuple 
tup3 = tup1 + tup2;
print tup3;
# Output results of the above examples: 
#(12, 34.56, 'abc', 'xyz')

Delete tuples
Element values in tuples are not allowed to be deleted, but we can use the del statement to delete the entire tuple, as shown in the following example:
#!/usr/bin/python
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : "
print tup;

After the above instance tuples are deleted, the output variable will have the exception information as follows:
# (' physics', 'chemistry, 1997, 2000)
# After deleting tup:
#Traceback (most recent call last):
#   File "test.py", line 9, in < The module >
#       Print tup.
#NameError: name 'tup' is not defined[/code]
Tuple operator
Like strings, tuples can be evaluated with + and * signs. This means that they can be combined and replicated, resulting in a new tuple.

Six, tuple index, interception
Since a tuple is also a sequence, we can either access the element at the specified location in the tuple or intercept a segment of the element in the index, as shown below:
Tuples:

L = ('spam', 'Spam', 'SPAM!')


Seven, no close separator
Any unsigned object, separated by a comma, is a tuple by default, as shown in the following example:

#!/usr/bin/python
print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;

The above example allows results:
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2

Tuple built-in function
Python tuples contain the following built-in functions
1. CMP (tuple1, tuple2) : compare two tuple elements.
2. Len (tuple) : calculate the number of tuple elements.
3. Max (tuple) : returns the maximum value of an element in a tuple.
4. Min (tuple) : returns the minimum value of an element in a tuple.
5. Tuple (seq) : converts a list to a tuple.

Nine, another interpretation

A tuple is very similar to a list, but once a tuple is initialized, it cannot be changed. For example, the name of a classmate is also listed:

>>> classmates = ('Michael', 'Bob', 'Tracy')

Now, the classmates tuple can't change, and it doesn't have methods like append() or insert(). The other methods to get the elements are the same as list, you can normally use classmates[0], classmates[-1], but cannot assign to other elements.
What's the point of an immutable tuple? Because the tuple is immutable, the code is more secure. If possible, use a tuple instead of a list.
The tuple trap: when you define a tuple, the elements of the tuple must be determined at the time of definition, such as:

>>> t = (1, 2)
>>> t
(1, 2)

If you want to define an empty tuple, you can write () :
>>> t = ()
>>> t
()

However, to define a tuple with only one element, if you define it this way:
>>> t = (1)
>>> t
1

It's not a tuple, it's a 1! This is because the parenthesis () can represent both a tuple and a parenthesis in a mathematical formula, which leads to ambiguity, so Python states that in this case, if you calculate by the parenthesis, the result will be 1.
Therefore, the definition of a tuple with only 1 element must be added with a comma, to disambiguate:
>>> t = (1,)
>>> t
(1,)

Python also adds a comma when displaying a one-element tuple, lest you mistake it for a mathematical parenthesis.

Here's a "mutable" tuple:

>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])

This tuple is defined with three elements, 'a', 'b' and a list. Isn't it true that a tuple once defined is immutable? Why did it change?

Wait, let's look at the three elements that a tuple contains when it is defined:
< img Alt = border = 0 tuple - 0 SRC = "/ / files.jb51.net/file_images/article/201403/2014031116262410.png" >
When we change the elements 'A' and 'B' of list to 'X' and 'Y', the tuple becomes:
< img Alt = border = 0 SRC = "/ / files.jb51.net/file_images/article/201403/2014031116262411.png" tuple - 1 >
On the surface, the elements of the tuple do change, but it's not the elements of the tuple that change, it's the elements of the list. The list that a tuple started out pointing to didn't change to another list, so what a tuple means by "invariant" is that every element of a tuple has the same point forever. If you're pointing to 'a', you can't change it to 'b', if you're pointing to a list, you can't change it to point to some other object, but the list itself is mutable!
Now that you understand the point invariant, what do you do to create a tuple with the same content? You have to make sure that every element of the tuple itself doesn't change.


Related articles: