Create tuple: Tuples can be created using parentheses ():
my_tuple = () my_tuple = (1, 2, 3)
The empty tuple represents a tuple with a length of 0.
Access tuple elements: Similar to lists and strings , tuple elements can be accessed using indexes :
my_tuple = (1, 2, 3) print(my_tuple[0])# 输出:1
Immutability: A tuple is immutable, which means its elements or size cannot be changed after creation. Attempting to do so raises TypeError:
my_tuple = (1, 2, 3) my_tuple[0] = 4# TypeError: "tuple" object does not support item assignment
Basic operations: Tuples support a variety of basic operations, including:
my_tuple1 = (1, 2, 3) my_tuple2 = (4, 5, 6) new_tuple = my_tuple1 + my_tuple2# (1, 2, 3, 4, 5, 6)
my_tuple = (1, 2, 3) repeated_tuple = my_tuple * 3# (1, 2, 3, 1, 2, 3, 1, 2, 3)
Advantages of tuples:
Application of tuples: Tuples are widely used in python, including:
Summarize: Tuple is a powerful and useful data structure in Python, which provides the function of immutable sequence. They are used in a wide variety of applications, including data grouping, function argument passing, and hash table keys. Understanding the properties and operations of tuples is crucial to using Python Programming effectively.
The above is the detailed content of Tuples Guide: A comprehensive understanding of immutable sequences in Python. For more information, please follow other related articles on the PHP Chinese website!