In this tutorial, we will learn about the Tuple in Python. Its types, and how to use them with the help of examples.
Tuple can store both homogeneous & heterogeneous data. Insertion order is preserve it means in which order we insert data same order output is print. Tuple allows duplicate objects. The tuple contains forward indexing & backward indexing. This is immutable modifications are not allow. Declared within the parenthesis ( ). Tuples are order sequences, each element has a specific order that will never change.
Creating of Tuple in Python
To create a tuple, all the objects must be enclose in parenthesis (), each one separate by a comma. A tuple can have any number of items and they may be of different types like integer, float, list, etc.
Input Value
Creates of Tuple in Python# Empty tuple tuple1 = () print(tuple1) # integers tuple2 = (1, 2, 3) print(tuple2) # mixed datatypes tuple3 = (1, 2.8,"Basicengineer") print(tuple3) # nested tuple tuple4 = ([2, 4, 6],"Basicengineer", (8, 10, 12)) print(tuple4)
Let’s run the code
Accessing of Tuples in Python
We can use the index operator [] to access an item in a tuple. Python allows negative indexing for its sequences.
Example of Accessing of Tuples in Python
Example of Accessing of Tuples in Python# indexing basicengineer letters = ("b", "a", "s", "i", "c", "e", "n", "g", "i","n","e","e","r") print("indexing") print(letters[3]) print(letters[7]) # negative indexing letters = ("b", "a", "s", "i", "c", "e", "n", "g", "i","n","e","e","r") print("negative indexing") print(letters[-3]) print(letters[-7])
Let’s run the code
Method of Tuple in Python
Method | Description |
index() | Find in the tuple and returns the index of the given value where it’s available |
count() | Returns the frequency of occurrence of a specified value |
len() | Returns length of the tuple or size of the tuple |
all() | Returns true if all element are true or if tuple is empty |
any() | return true if any element of the tuple is true. if tuple is empty, return false |
max() | return maximum element of given tuple |
min() | return minimum element of given tuple |
tuple() | Convert an iterable to a tuple. |
Concatenation and Slicing in Tuple
Example of Concatenation and Slicing in Tuple
A Example of Concatenation and Slicing in Tuple# Concatenation Tuple1 = (0, 1, 2, 3) Tuple2 = ('Basic', 'Engineer', 'Hello', 'Student') Tuple3 = Tuple1 + Tuple2 print("Concatenation") print(Tuple3) # Slicing Tuple4 = tuple('Basic Engineer') print("Slicing") print(Tuple4[3:]) print(Tuple4[::-5]) print(Tuple4[4:9])
If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.
To know more about Python Wikipedia please click here .
Stay Connected Stay Safe, Thank you
0 Comments