Half an hour Python play tuple

Posted by js_280 on Sun, 02 Jan 2022 13:58:09 +0100

How does Xiaobai become a python data analyst

Day 9 - tuple

List and tuple are container data types, that is, a variable can hold multiple data. List is a variable data type and tuple is an immutable data type, so the methods of adding elements, deleting elements, emptying and sorting in list are not tenable for tuple.

Read only, tuples are usually defined using () literal syntax.

Advantages: immutable types are more suitable for multi-threaded environments,

Immutable types are superior to the corresponding variable types in terms of creation time and occupied space

definition

In Python, tuples are also a sequence 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 also recommended to use this method to create tuples. Tuple types support the same operators as lists.

Tuple related operations

# Create tuples (argument syntax)
fruits = ('h', 'k', 'u', 'p', 'f',)
print(type(fruits))
# Repeated calculation
print(fruits * 3)

# Merge operation
fruits1 = ('5', '8', '7')
fruits3 = fruits1 + fruits
print(fruits3)

# Slice, index
print(fruits[2:])
print(fruits3[::-1])
# Indexes
print(fruits[-1])
print(fruits[3])

# Number of subscript elements to read
print(fruits3.index('5'))
print(fruits3.count('5'))

# View the type of variable
print(type(fruits))  #  <class 'tuple'>

# View the number of elements in the tuple
print(len(fruits))    #  5

# Get the elements in the tuple through index operation
print(fruits[0], fruits[-5])         # h h 
print(fruits[3], fruits[-2])         # p p

# Loop through elements in tuples
for x in fruits:
    print(fruits)

If there are two elements in a tuple, we call it a tuple; If there are five elements in a tuple, we call it a quintuple. and so on;

’'()' represents an empty tuple, but if there is only one element in the tuple, you need to add a comma. Otherwise (), it is not the literal syntax of the tuple, but the 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'>

Application of tuples

1: Packaging and unpacking operations.

Unpacking: (split the elements of tuples.) When we assign a tuple to multiple variables, the tuple will be unpacked into multiple values and then assigned to the corresponding variables respectively. Unpacking syntax holds for all sequences, which means that unpacking syntax can be used for strings, lists and range sequences returned by the range function we mentioned earlier.

Packing: (multiple elements are grouped into meta groups) tuples when we assign multiple comma separated values to a variable, multiple values will be packed into a tuple type

# pack
a = 1, 5, 6, 8, 10, 12
print(type(a), a)    # <class 'tuple'> (1, 5, 6, 8, 10, 12)
# # Unpack
a, b, c = (5, 6, 8)
print(a)
print(b)
print(c)


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, b, c = (5, 6, 8, 7, 20)
print(a)
print(b)
print(c)

Solution: if the number of variables is less than the number of elements, you can use the asterisk expression '*'.

# *c group the rest into a list and give it to c
a, b, *c = (5, 6, 8, 7, 20)
print(a)    # 5
print(b)    # 6
print(c)    # [8,7,20]

# Start and end
a, *b, c = (5, 6, 8, 7, 20)
print(a)
print(c)

#Take the last two
*a, b, c = (5, 6, 8, 7, 20)
print(b)
print(c)


Unpacking syntax holds for all sequences, which means that unpacking syntax can be used for strings, lists and range sequences returned by the range function we mentioned earlier.

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: Exchange the values of two variables

Exchanging the values of two variables is a classic case in programming languages. In many programming languages, exchanging the values of two variables requires the help of an intermediate variable. If there is no intermediate variable, it needs to be realized by using 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
a, b, c = b, c, a

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.

# exchange
a, b = b, a
a, b, c = b, c, a

d = 0
a, b, c, d = b,  c, d, a
3: Let the function return multiple values.

Sometimes a function may need to return multiple values after execution. At this time, tuple type should be a convenient choice. For example, write a function to find the maximum and minimum values in the list

# def defines a function; find_max_and_min (function name); items (variable name)
def find_max_and_min(items):
    """Find the largest and smallest elements in the list
    :param items: list
    :return: A binary consisting of the largest and smallest elements
    """
    max_one, min_one = items[0], items[0]
    for item in items:
        if item > max_one:
            max_one = item
        elif item < min_one:
            min_one = item
    return max_one, min_one

# max_num, min_num by calling this function, the input variable items = [1, 3, 5, 8]
max_num, min_num = find_max_and_min([1, 3, 5, 8])
print(max_num, min_num)

There are two values in the return statement of the above function. These two values will be assembled into a binary and then returned. So call find_ max_ and_ The Min function will get the binary. If you like, you can assign two values in the binary to two variables respectively through unpacking syntax.

4. Comparison of tuples and lists

Here is another question worth exploring. Python already has list types. Why do you need tuples?

  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)'))

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

# Convert tuples to lists
info = ( 175, True, 'good person')
print(list(info))       # [175, True, 'good man']
# Convert list to tuple
fruits = ['apple', 'banana', 'orange']
print(tuple(fruits))    # ('apple', 'banana', 'orange')

Topics: Python