Home >Backend Development >Python Tutorial >How to get data in tuple in python
To get the data in the tuple, you can access the elements in the tuple through the index number or slicing.
Access elements in a tuple by index number:
my_tuple = (1, 2, 3, 4, 5) print(my_tuple[0])# 输出 1 print(my_tuple[3])# 输出 4
Access elements in a tuple through slicing:
my_tuple = (1, 2, 3, 4, 5) print(my_tuple[1:4])# 输出 (2, 3, 4) print(my_tuple[:3]) # 输出 (1, 2, 3) print(my_tuple[2:]) # 输出 (3, 4, 5)
You can use negative index numbers to calculate the index from the end of the tuple, for example -1
represents the last element, -2
represents the penultimate element, and so on .
It should be noted that tuples are immutable, that is, the elements in the tuple cannot be modified.
The above is the detailed content of How to get data in tuple in python. For more information, please follow other related articles on the PHP Chinese website!