Common data structure - tuple

Keywords: data structure

1. Tuple

Tuple is also a sequence composed of multiple elements in a certain order. The difference between tuples and lists is that tuples are immutable types, which means that once variables of tuple type are defined, the elements in them can no longer be added or deleted, and the values of elements can't be modified. The () literal syntax is usually used to define tuples. It is recommended that you use this method to create tuples.

# Define a triplet
t1 = (30, 10, 55)
# Define a quad
t2 = ('Luo Hao', 40, True, 'Chengdu, Sichuan')

# View the type of variable
print(type(t1), type(t2))    # <class 'tuple'> <class 'tuple'>
# View the number of elements in the tuple
print(len(t1), len(t2))      # 3 4

# Get the elements in the tuple through index operation
print(t1[0], t1[-3])         # 30 30
print(t2[3], t2[-1])         # Chengdu, Sichuan Chengdu, Sichuan

# Loop through elements in tuples
for member in t2:

# Member operation
print(100 in t1)    # False
print(40 in t2)     # True

# Splicing
t3 = t1 + t2
print(t3)           # (30, 10, 55, 'Luo Hao', 40, True, 'Chengdu, Sichuan')

# section
print(t3[::3])      # (30, 'Luo Hao', 'Chengdu, Sichuan')

# Comparison operation
print(t1 == t3)    # False
print(t1 >= t3)    # False
print(t1 < (30, 11, 55))    # True

() represents an empty tuple, but if there is only one element in the tuple, a comma needs to be added. Otherwise, () does not represent the literal syntax of the tuple, but parentheses that change the operation priority. Therefore ('hello ',) and (100,) are a tuple, while ('hello') and (100) are just strings and integers.

# Empty tuple
a = ()
print(type(a))    # <class 'tuple'>
# Not a tuple
b = ('hello')
print(type(b))    # <class 'str'>
c = (100)
print(type(c))    # <class 'int'>
# One tuple
d = ('hello', )
print(type(d))    # <class 'tuple'>
e = (100, )
print(type(e))    # <class 'tuple'>

2. Application scenarios of tuples

2.1 packaging and unpacking

# pack
a = 1, 10, 100
print(type(a), a)    # <class 'tuple'> (1, 10, 100)
# Unpack
i, j, k = a
print(i, j, k)       # 1 10 100

During unpacking, if the number of unpacked elements does not correspond to the number of variables, a ValueError exception will be thrown. The error message is: too many values to unpack or not enough values to unpack.

a = 1, 10, 100, 1000
# i, j, k = a             # ValueError: too many values to unpack (expected 3)
# i, j, k, l, m, n = a    # ValueError: not enough values to unpack (expected 6, got 4)

One way to solve the problem that the number of variables is less than the number of elements is to use the asterisk expression. We used the asterisk expression when talking about the variable parameters of the function before. With the asterisk expression, we can make a variable receive multiple values. The code is as follows. It should be noted that the variable decorated with an asterisk expression will become a list with 0 or more elements in the list. Also, in unpacking syntax, the asterisk expression can only appear once.

a = 1, 10, 100, 1000
i, j, *k = a
print(i, j, k)          # 1 10 [100, 1000]
i, *j, k = a
print(i, j, k)          # 1 [10, 100] 1000
*i, j, k = a
print(i, j, k)          # [1, 10] 100 1000
*i, j = a
print(i, j)             # [1, 10, 100] 1000
i, *j = a
print(i, j)             # 1 [10, 100, 1000]
i, j, k, *l = a
print(i, j, k, l)       # 1 10 100 [1000]
i, j, k, l, *m = a
print(i, j, k, l, m)    # 1 10 100 1000 []

Unpacking syntax holds for all sequences, which means that unpacking syntax can be used for lists and range sequences returned by the range function we mentioned earlier. You can try to run the following code to see what results will appear.

a, b, *c = range(1, 10)
print(a, b, c)
a, b, c = [1, 10, 100]
print(a, b, c)
a, *b, c = 'hello'
print(a, b, c)

2.2 exchange the values of two variables

In many programming languages, the exchange of the values of two variables can only be achieved with the help of an intermediate variable. If the intermediate variable is not used, it needs to be realized by more obscure bit operation. In Python, exchanging the values of two variables a and b only requires the code shown below.

a, b = b, a

Similarly, if you want to exchange the values of three variables a, b and c, that is, b is assigned to a, c is assigned to b, and a is assigned to c, you can also do the same.

a, b, c = b, c, a

It should be noted that the packing and unpacking syntax is not used above. There is rot in Python bytecode instructions_ Two and rot_ Instructions such as three can realize this operation, and the efficiency is very high. However, if the values of more than three variables need to be exchanged in turn, there is no directly available bytecode instruction at this time. The principle of execution is the packaging and unpacking operations explained above.

3. Tuple and list comparison

The methods of adding elements, deleting elements, emptying and sorting in the list are not tenable for tuples. However, both lists and tuples can be spliced, member operated, indexed and sliced

  1. Tuples are immutable types. Immutable types are more suitable for multi-threaded environments because they reduce the synchronization overhead of concurrent access variables. On this point, we will discuss it in detail later when we explain multithreading.

  2. Tuples are immutable types. Usually, immutable types are better than the corresponding variable types in creation time and space. We can use the getsizeof function of sys module to check how much memory space is occupied by tuples and lists holding the same elements. We can also use the timeit function of the timeit module to see how long it takes to create tuples and lists that hold the same elements. The code is as follows.

    import sys
    import timeit
    a = list(range(100000))
    b = tuple(range(100000))
    print(sys.getsizeof(a), sys.getsizeof(b))    # 900120 800056
    print(timeit.timeit('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))
    print(timeit.timeit('(1, 2, 3, 4, 5, 6, 7, 8, 9)'))

    three   Tuples and lists in Python can be converted to each other. We can do this through the following code.

# Convert tuples to lists
info = ('Luo Hao', 175, True, 'Chengdu, Sichuan')
print(list(info))       # ['Luo Hao', 175, True, 'Chengdu, Sichuan']
# Convert list to tuple
fruits = ['apple', 'banana', 'orange']
print(tuple(fruits))    # ('apple', 'banana', 'orange')

Posted by wit77 on Mon, 08 Nov 2021 14:29:15 -0800