Tuples in Python
What are the Tuple?
Tuples in Python are similar to lists. Tuples can store multiple values of different data types, such as integers, strings, and other data structures like lists or tuples.
Tuples can be used to group values together, making it easier to work with them.
Tuple properties
Tuple can be enclosed with Parentheses or Round Brackets, ( ) and the values inside the tuple separated with commas.
fruits = ('apple', 'banana', 'cherry')
print(fruits)
//Output
('apple', 'banana', 'cherry')
Python Tuple are mutable
This means that once a tuple is created, its elements cannot be changed, added, or removed. When you try to change the elements of a tuple, you will get a Type Error.
For example:
fruits = ('apple', 'banana', 'cherry')
fruits[0] = 'pear' # This will raise a TypeError
print(fruits)
//Output
TypeError: 'tuple' object does not support item assignment
Though a tuple can store similar data it is commonly used for storing dissimilar data.
a = () # empty tuple
b = (10,) # tuple with one item, after 10 is necessary
c = ("John", 3.5, 10) # tuple with dissimilar items
d = (1, 2, 3, 4, 5) # tuple with similar items
print(a)
print(b)
print(c)
print(d)
//Output
()
(10,)
('John', 3.5, 10)
(1, 2, 3, 4, 5)
While creating the tuple b, if we do not use the comma after 10, b is treated to be of type int.
While initializing a tuple, we may drop ( ).
a = 'John', 3.5, 10 # tuple with multiple items
print(a) # without bracket also tuple can be execute
print(type(a)) # a is of the type tuple
//Output
('John', 3.5, 10)
<class 'tuple'>
Tuple slicing
In Python, tuple slicing is the process of accessing a sub-tuple from an existing tuple. Tuple slicing is similar to list slicing and is performed using the square bracket notation, just like with lists.
Here's an example of slicing a tuple in Python:
fruits = ('apple', 'banana', 'cherry', 'orange')
print(fruits[1:3])
//output
('banana', 'cherry')
In this example, the slice 'fruits[1:3]'
creates a new tuple that contains the second and third elements (index 1 and 2) of the original tuple 'fruits'
.
You can also use negative indices to count from the end of the tuple:
fruits = ('apple', 'banana', 'cherry', 'orange')
print(fruits[-2:])
//output
('cherry', 'orange')
Additionally, you can specify a step value to skip elements while slicing:
fruits = ('apple', 'banana', 'cherry', 'orange')
print(fruits[::2])
//output
('apple', 'cherry')
Tuple slicing is a powerful and flexible tool for accessing and manipulating sub-tuples in Python. It can be used to extract and process data in a variety of ways, making it an important part of the Python language.Tuple methods
Python tuple has two built-in methods that can you use.
Method | Description |
Returns the number of times a specified value occurs in a tuple | |
Searches the tuple for a specified value and returns the position of where it was found |
No comments:
Post a Comment