Introduction
Python Data Types & Operators
Conditional Statements
Python Loops
Python Strings
Python Lists
Python Tuple
In Python, tuple indexes refer to the positions of elements within a tuple. You can access elements in a tuple using these indexes, where the index of the first element is 0
, the second element is 1
, and so on.
Tuple Indexing
Positive Indexing:
- The index starts at
0
for the first element,1
for the second element, and continues onward. - Example:
- The index starts at
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Output: 10 (First element)
print(my_tuple[1]) # Output: 20 (Second element)
print(my_tuple[2]) # Output: 30 (Third element)
Negative Indexing:
- Negative indexing allows you to access elements starting from the end of the tuple. The index
-1
refers to the last element,-2
refers to the second-to-last element, and so on. - Example:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[-1]) # Output: 50 (Last element)
print(my_tuple[-2]) # Output: 40 (Second to last element)
print(my_tuple[-3]) # Output: 30
Indexing with Slicing
You can also use slicing to get sub-tuples (i.e., a subset of the tuple) by specifying a range of indexes. The syntax for slicing is tuple[start:stop:step]
.
Basic Slicing:
- Retrieves a range of elements from
start
tostop - 1
. - Example:
- Retrieves a range of elements from
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[1:4]) # Output: (20, 30, 40) (Elements from index 1 to index 3)
Slicing with Step:
- You can use the
step
parameter to get every nth element in the specified range. - Example:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[::2]) # Output: (10, 30, 50) (Every 2nd element)
Negative Index Slicing:
- You can use negative indices to slice from the end of the tuple.
- Example:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[-3:]) # Output: (30, 40, 50) (Elements from index -3 to the end)
Reversing a Tuple Using Slicing:
- You can reverse a tuple using the
[::-1]
slice. - Example:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[::-1]) # Output: (50, 40, 30, 20, 10)
Tuple Summary:
- Positive Indexing: Starts from
0
for the first element and increases by1
. - Negative Indexing: Starts from
-1
for the last element and decreases by1
as you move left. - Slicing: You can slice a tuple to extract a part of it using
[start:stop:step]
. - Reversing: You can reverse a tuple using slicing with
[::-1]
.