Brothers of lists in Python-tuples

Definition of tuple

Tuples are similar to lists, except that the elements of tuples cannot be modified.

Tuples a sequence of a plurality of elements, with parentheses ()to declaration defines, for storing a string of information, used between the data ,separator.

The index of the tuple starts from 0, and the index is the position number of the data in the tuple.

Tuples can also be regarded as immutable lists. Normally, tuples are used to store content that does not need to be modified.

Let's declare a tuple

info = ("zhangsan", 18, 1.75)

When the tuple contains only one element, you need to add a comma after the element.

If you define a tuple with only one element without a comma, Python will not consider it a tuple, but according to the data type of the element itself.

info = (50, )

Common operations on tuples

Value and index of tuple

info = ("zhangsan", 18, 1.75, "zhangsan")
print(info[0])
# 已经知道数据的内容,希望知道该数据在元组中的索引
print(info.index("zhangsan"))

Statistics and counting of tuples

info = ("zhangsan", 18, 1.75, "zhangsan")
print(info.count("zhangsan"))
# 统计元组中包含元素的个数
print(len(info))

Application scenarios of tuples

Although for in can be used to traverse tuples, in actual development, unless the data type in the tuple can be confirmed, there are not many loop traversal requirements for tuples.

More application scenarios are as follows:

1. Function parameters and return values, a function can receive any number of parameters, or return multiple data at once (about functions, we will introduce in a later article).

2. Format string. The parentheses after the format string are ()essentially a tuple.

info = ("zhangsan", 18)
print("%s 的年龄是 %d" % info)

3. The list cannot be modified to protect data security.

Conversion between tuples and lists

Use the list function to convert tuples into lists

list(元组) 

Use tuple function to convert list into tuple

tuple(列表)

The pilgrimage of programming

Guess you like

Origin blog.csdn.net/beyondamos/article/details/107971928