TUPLES INTRODUCTION
TUPLES
In Python, a tuple is an immutable sequence type that can store a collection of elements. Tuples are similar to lists, but the main difference is that tuples are immutable, meaning their elements cannot be modified after creation. Here's an overview of tuples in Python:
1.Creating Tuples: Tuples are created by enclosing comma-separated values within parentheses
()
. my_tuple = (1, 2, 3)
Tuples can also be created without parentheses, using just commas.
Example:
another_tuple = 4, 5, 6
2.Accessing Elements:
Tuple elements can be accessed using indexing. The index starts from 0 for the first element.
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
Tuples also support negative indexing, where -1 refers to the last element, -2 refers to the second-last element, and so on.
Example:
my_tuple = (1, 2, 3)
print(my_tuple[-1]) # Output: 3
Tuple packing refers to creating a tuple by assigning values to a single variable.
Example:
my_tuple = 1, 2, 3
3.Tuple Packing and Unpacking:
Tuple unpacking allows you to assign tuple elements to individual variables.
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
4.Tuple Operations:
Since tuples are immutable, you cannot modify their elements directly. However, you can perform various operations on tuples, including concatenation and repetition.
Tuple Operations:
- Concatenation:
- Repetition:
5.Tuple Methods:
Tuples provide a few methods for basic operations like counting occurrences and finding the index of an element. Some commonly used tuple methods include
count()
and index()
.
Comments
Post a Comment