How to get data in tuple in python

王林
Release: 2024-03-01 17:34:31
forward
639 people have browsed it

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
Copy after login

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)
Copy after login

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!

Related labels:
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