Python data type - tuple

tuple

A tuple is an ordered and immutable collection, and duplicate members are allowed in the tuple.

create tuple

create empty tuple

In Python, ()represents an empty tuple. for example:

a = ()
print(type(a))  # <class 'tuple'>
print(a)        # ()

In addition, tuplean empty tuple can also be created by means of for example:

a = tuple()
print(type(a))  # <class 'tuple'>
print(a)        # ()

Create a non-empty tuple

()The initial value of the tuple can be set in the tuple when it is created . for example:

a = (1, 2, 3, 4, 5)
print(type(a))  # <class 'tuple'>
print(a)        # (1, 2, 3, 4, 5)

It should be noted that the elements stored in the tuple can be of different types. for example:

a = (1, 'hello', True, [4, 5, 6])
print(type(a))  # <class 'tuple'>
print(a)        # (1, 'hello', True, [4, 5, 6])

Modify tuple elements

The function of tuple is basically the same as that of list, but tuple is an immutable collection, so tuple does not provide any method to modify tuple. If you want to modify the values ​​in a tuple, you can convert the tuple to a list, change the list and then convert it back to a tuple. for example:

a = (1, 2, 3, 4)
tmp = list(a)   # 将元组转换成列表
tmp[0] = 10     # 更改列表
a = tuple(tmp)  # 将列表转换回元组
print(a)        # (10, 2, 3, 4)

Suggestion: Although this method can modify the tuple, it is not recommended to do so. If the elements in a sequence need to be modified, it is best to store them directly in a list.

Find tuple elements

in and in not operators

Use the in and in not operators to determine whether an element exists in the tuple. for example:

a = (1, 2, 3, 4)
print(1 in a)       # True
print(10 in a)      # False
print(1 not in a)   # False
print(10 not in a)  # True

index method

The index method can also be used to determine whether an element exists in the tuple. for example:

a = (1, 2, 3, 4)
print(a.index(3))  # 2
# print(a.index(10))  # 不存在,抛异常

Note: When using the index method, if the element to be found is in the tuple, the subscript of the element will be returned, otherwise an exception will be thrown.

Subscript access to tuple elements

Access tuple elements

[]The element at the specified subscript position can be obtained through the subscript access operator . for example:

a = (1, 2, 3, 4)
print(a[2])  # 3

Note: If the value of the specified subscript exceeds the maximum subscript in the tuple, an exception will be thrown.

negative index

[]The subscript specified in the subscript access operator can take a negative number, which we call a negative index. The negative index actually starts from the last element of the tuple and goes forward, in order of -1, -2, -3, .... For example:
insert image description here
So if you want to access the last element of the tuple, you can directly access the element with the subscript -1. for example:

a = (1, 2, 3, 4)
print(a[-1])  # 4

iterate over tuple elements

for loop traversal

When traversing a tuple in a for loop, you can directly traverse the tuple as an iterable object, or you can traverse the subscripts of the elements in the tuple, and then use the subscript access operator to access each element in turn []. for example:

a = (1, 2, 3, 4)
# 方式一
for elem in a:
    print(elem)

# 方式二
for i in range(len(a)):
    print(a[i])

To explain: the number of elements in the tuple can be obtained through the len function.

while loop traverses

[]It is also possible to traverse the subscripts of the elements in the tuple in a while loop, and then access each element in turn through the subscript access operator . for example:

a = (1, 2, 3, 4)
i = 0
while i < len(a):
    print(a[i])
    i += 1

subtuple extraction

[start subscript: end subscript]

[起始下标 : 结束下标]A set of elements that can be extracted from a tuple starting from the start subscript to the end subscript . for example:

a = (1, 2, 3, 4)
print(a[1:3])  # (2, 3)

Note: The extracted sub-tuple contains the elements of the start subscript, but does not include the element of the end subscript (close before and open after).

Omit bounds when slicing

The process of extracting sub-tuples is also called the process of slicing, and [起始下标 : 结束下标]the start subscript or the end subscript can be omitted when slicing in the way.

  • If [起始下标 : ]sliced ​​in a way, the elements in the subtuple include the element with the starting subscript and its subsequent elements.
  • If [ : 结束下标]sliced ​​in , the elements in the subtuple include all elements up to the closing subscript.
  • If [ : ]sliced ​​in , the elements in the subtuple include all elements in the original tuple.

Slice example:

a = (1, 2, 3, 4)
print(a[1:])   # (2, 3, 4)
print(a[:2])   # (1, 2)
print(a[:-1])  # (1, 2, 3)
print(a[::])   # (1, 2, 3, 4)

Note: Negative indices can also be used when slicing.

Specify the step size when slicing

Slicing in [起始下标 : 结束下标 : 步长]the way can specify the step size, that is, how many steps the subscript increments after each element is accessed. for example:

a = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
print(a[::1])     # (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
print(a[::2])     # (1, 3, 5, 7, 9)
print(a[::3])     # (1, 4, 7, 0)
print(a[1:-1:2])  # (2, 4, 6, 8)

In addition, the step size specified when slicing can also be a negative number, which means that elements are extracted from the back to the front. for example:

a = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
print(a[::-1])  # (0, 9, 8, 7, 6, 5, 4, 3, 2, 1)
print(a[::-2])  # (0, 8, 6, 4, 2)

Subscript out of bounds problem when slicing

If the subscript filled in when slicing exceeds the valid range, no exception will be thrown after running the program, but elements that meet the requirements will be extracted as much as possible. for example:

a = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
print(a[1:100])  # (2, 3, 4, 5, 6, 7, 8, 9, 0)

splice tuple

Use + to concatenate tuples

Use + to concatenate two tuples together. for example:

a = (1, 2, 3)
b = (4, 5, 6)
c = a + b
print(a)  # (1, 2, 3)
print(b)  # (4, 5, 6)
print(c)  # (1, 2, 3, 4, 5, 6)

Note: After using + splicing, a new tuple will be generated, and this operation will not affect the two original tuples.

Use += to concatenate tuples

Use += to concatenate one tuple after another. for example:

a = (1, 2, 3)
b = (4, 5, 6)
a += b
print(a)  # (1, 2, 3, 4, 5, 6)
print(b)  # (4, 5, 6)

Explain:

  • Because tuples are an immutable collection, tuples do not provide an extend method to splice one tuple behind another.
  • a += bEquivalently a = a + b, during the splicing process, the spliced ​​tuples will be constructed first, then the original tuples of a will be released, and then the spliced ​​tuples will be assigned to a. This process does not modify the tuples originally managed by a.

Summary of commonly used interfaces for tuples

Tuple operations:

tuple operation Way
subtuple extraction thistuple[start:end:step](Front closed and rear open)
tuple check inandin not
tuple concatenation +and+=
tuple length len()function

Member functions for tuples:

member function Function
index Returns the subscript (first occurrence) of the element with the specified value
count Returns the number of elements with the specified value

Guess you like

Origin blog.csdn.net/chenlong_cxy/article/details/127651924