Decrypting tuples: valuable knowledge about immutable containers in Python

王林
Release: 2024-03-24 16:01:25
forward
943 people have browsed it

解密元组:Python 中不可变容器的宝贵知识点

Create tuple:

  • Use parentheses: (), for example: my_tuple = (1, 2, 3)
  • Use commas to separate elements: my_tuple = 1, 2, 3

Access tuple elements:

  • Use index : my_tuple[index], for example: my_tuple[1]
  • Use slices: my_tuple[start:end], for example: my_tuple[1:2]

Immutability of tuples:

  • The contents of a tuple cannot be changed once created.
  • Attempting to modify an element will raise TypeError.
  • Reallocating tuples creates new objects but does not modify existing tuples.

Hash and comparability of tuples:

  • A tuple is hashed, and its hash value is calculated from the hash value of its elements.
  • Tuples are comparable, and their comparison is based on the order comparison of elements.

Tuple operations:

  • Adding operation: The operator joins two tuples.
  • Repeat operation: * The operator repeats the tuple the specified number of times.
  • Counting operation: count() method returns the number of times a specific element appears in the tuple.
  • Index operation: index() The method returns the index of the specified element.

Practical functions of tuples:

  • are used in dictionaries as keys because they are immutable and hashable.
  • Used to traverse multiple values ​​in a loop.
  • As function parameters and return values ​​to ensure data integrity.

Example:

# 创建元组
my_tuple = (1, 2, 3)

# 访问元素
print(my_tuple[1])# 输出:2

# 切片元组
print(my_tuple[1:2])# 输出:(2,)

# 增合元组
new_tuple = my_tuple + (4, 5)
print(new_tuple)# 输出:(1, 2, 3, 4, 5)

# 计数元素出现次数
print(new_tuple.count(2))# 输出:1
Copy after login

in conclusion:

A tuple is a useful immutable container in python, used to store a sequence of ordered values. Understanding valuable knowledge about their creation, access, and operation is critical to utilizing them effectively. The immutability of tuples ensures data integrity, while their hashing and comparability make them versatile in dictionaries and functions.

The above is the detailed content of Decrypting tuples: valuable knowledge about immutable containers in Python. For more information, please follow other related articles on the PHP Chinese website!

source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template