Home >Backend Development >Python Tutorial >Tuples Revealed: The Ultimate Guide to Immutable Containers in Python
Tuple is an immutable data structure in python, used to store ordered sequence of data. Similar to lists, tuples can contain a variety of element types, including numbers, strings, lists, and even other tuples. However, unlike lists, tuples cannot be modified.
Create tuple
my_tuple = (1, "two", 3.14)
, such as:
<pre class="brush:python;toolbar:false;">my_tuple = tuple([1, "two", 3.14])</pre>
The main feature of tuples is their immutability. Once created, elements in a tuple cannot be modified, added, or removed. This makes tuples ideal for storing data that needs to be protected or as function parameters.
Accessing tuple elements
my_tuple[0] # 返回第一个元素 my_tuple[-1] # 返回最后一个元素
my_tuple[0:2] # 返回前两个元素 my_tuple[2:] # 返回从第三个元素开始的所有元素
Although tuples are immutable, there are still some operations that can be performed on them:
: Connect two or more tuples, such as:
new_tuple = my_tuple + (4, "five")
: Create a new copy of the tuple, such as:
new_tuple = my_tuple[:]
in): Check whether a value is contained in a tuple, such as:
if "two" in my_tuple:
print("Found "two" in the tuple")
: Use a for loop or iterator to traverse the elements in the tuple, such as:
for element in my_tuple:
print(element)
Tuples are often used as function parameters because they are immutable and help prevent accidental modification. Functions can access elements in a tuple using subscripts or pieces.
Tuple vs. ListTuples are immutable, while lists are mutable.
[]
.
The elements of a tuple can only be accessed through subscripts or segments, while the elements of a list can be modified and added. Prefer using tuples to store data that needs to be protected or immutable.
The above is the detailed content of Tuples Revealed: The Ultimate Guide to Immutable Containers in Python. For more information, please follow other related articles on the PHP Chinese website!