Tuple
- Tuples are used to store multiple items in a single variable.
- Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
- A tuple is a collection which is ordered and unchangeable.
- Tuples are written with round brackets.
# Note : In case of list, we use square
# brackets []. Here we use round brackets ()
t = (10, 20, 30)
print(t)
print(type(t))
Characteristics of Tuples in Python.
- Like Lists, tuples are ordered and we can access their elements using their index values
- We cannot update items to a tuple once it is created.
- Tuples cannot be appended or extended.
- We cannot remove items from a tuple once it is created.
Example
t = (1, 2, 3, 4, 5)
# tuples are indexed
print(t[1])
print(t[4])
# tuples contain duplicate elements
t = (1, 2, 3, 4, 2, 3)
print(t)
# updating an element (Note:It will throw as tuple is not changeable)
t[1] = 100
print(t)
Accessing Values in Python Tuples
Tuples in Python provide two ways by which we can access the elements of a tuple.
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.
t = (10, 5, 20)
print("Value in t[0] = ", t[0])
print("Value in t[1] = ", t[1])
print("Value in t[2] = ", t[2])
Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python,
and here we will use the negative index within [].
t = (10, 5, 20)
print("Value in t[-1] = ", t[-1])
print("Value in t[-2] = ", t[-2])
print("Value in t[-3] = ", t[-3])
Different Operations Related to Tuples:
Traversing Items of Python Tuples
Like List Traversal, we can traverse through a tuple using for loop.
# Define a tuple
t = (1, 2, 3, 4, 5)
# Traverse through each item in the tuple
for x in t:
print(x, end=" ")
Concatenation of Python Tuples
To Concatenation of Python Tuples, we will use plus operators(+).
# Code for concatenating 2 tuples
t1 = (0, 1, 2, 3)
t2 = ('python', 'Great')
# Concatenating above two
print(t1 + t2)
Nesting of Python Tuples
A nested tuple in Python means a tuple inside another tuple.
# Code for creating nested tuples
t1 = (0, 1, 2, 3)
t2 = ('python', 'is Boss')
t3 = (t1, t2)
print(t3)
Repetition Python TuplesWe can create a tuple of multiple same elements from a single element in that tuple.# Code to create a tuple with repetitiont = ('python',)*3print(t)Slicing Tuples in PythonSlicing a Python tuple means dividing a tuple into small tuples using the indexing method. In this example, we slice the tuple from index 1 to the last element. In the second print statement, we printed the tuple using reverse indexing. And in the third print statement, we printed the elements from index 2 to 4.# code to test slicingt = (0 ,1, 2, 3)print(t[1:])print(t[::-1])print(t[2:4])Note: In Python slicing, the end index provided is not included.Deleting a Tuple in PythonIn this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error because after deleting the tuple, it will give a NameError.Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del keyword.# Code for deleting a tuplet = ( 0, 1)del tprint(t)Finding the Length of a Python TupleTo find the length of a tuple, we can use Python’s len() function and pass the tuple as the parameter.# Code for printing the length of a tuplet = ('python', 'geek')print(len(t))
Multiple Data Types With TupleTuples in Python are heterogeneous in nature. This means tuples support elements with multiple datatypes.# tuple with different datatypest = ("immutable", True, 23)print(t)Converting a List to a TupleWe can convert a list in Python to a tuple by using the tuple() constructor and passing the list as its parameters.# Code for converting a list and a string into a tuplea = [0, 1, 2]t = tuple(a)print(t)Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are taken as elements), and converts them to a tuple.Tuples in a LoopWe can also create a tuple with a single element in it using loops.# python code for creating tuples in a loopt = ('gfg',)# Number of time loop runsn = 5 for i in range(int(n)): t = (t,) print(t)Different Ways of Creating a Tuple· Using round brackets· Without Brackets· Tuple Constructor· Empty Tuple· Single Element Tuple· Using Tuple PackingUsing Round Bracketst = ("gfg", "Python") print(t)Output('gfg', 'Python')
Using Comma Separated# Creating a tuple without bracketst = 4, 5, 6print(t) # Output: (4, 5, 6)Output(4, 5, 6)
Using Tuple Constructor# Creating a tuple using the tuple() constructort = tuple([7, 8, 9])print(t) # Output: (7, 8, 9)Output(7, 8, 9)
Creating an Empty Tuple# Creating an empty tuplet = ()print(t) # Output: ()Output()Single Element Tuple# Creating a single-element tuplet = (10, ) # Comma is important hereprint(t) # Output: (10,)print(type(t))
# What if we do not use commat = (10) # This an integer (not a tuple)print(t) print(type(t))Output(10,)<class 'tuple'>10<class 'int'>
Tuple Packing# Tuple packinga, b, c = 11, 12, 13t = (a, b, c)print(t) # Output: (11, 12, 13)
Output(11, 12, 13)
No comments:
Post a Comment