深度阅读

How to access items of a tuple in Python

作者
作者
2023年08月22日
更新时间
7.98 分钟
阅读时间
0
阅读量

To access items of a tuple in Python, you can use indexing to refer to individual elements of the tuple. Indexing starts at 0 for the first element, 1 for the second element, and so on.

Here’s an example:

my_tuple = ('apple', 'banana', 'cherry')

# Access the first element of the tuple
print(my_tuple[0])   # Output: 'apple'

# Access the second element of the tuple
print(my_tuple[1])   # Output: 'banana'

# Access the third element of the tuple
print(my_tuple[2])   # Output: 'cherry'

In this example, we first define a tuple my_tuple containing three string elements. We then use indexing to access the first, second, and third element of the tuple, and print each one to the console.
Note that you cannot modify the individual elements of a tuple since tuples are immutable.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。