Tuples are a sequence of Python objects. A tuple is created by separating items with a comma. They are put inside the parenthesis “”(“” , “”)””.
Tuples are a sequence of Python objects. A tuple is created by separating items with a comma. They are put inside the parenthesis “”(“” , “”)””.
Welcome, aspiring data scientists and coding enthusiasts! Today, we embark on an exciting journey into the world of Python, with a focus on one of its core data structures – tuples. Tuples are a fundamental aspect of Python programming, and understanding them is crucial for anyone looking to excel in data science or any coding language. Let’s dive into the intricacies of tuples with simple explanations, engaging language, and, of course, plenty of code examples. Whether you’re a beginner or seeking a master’s level understanding, this guide has something for you.
A tuple is a collection type in Python that is ordered and immutable. This means that once a tuple is created, its elements cannot be changed, removed, or added to. Tuples are written with round brackets `()` and can contain mixed data types, including integers, strings, and even other tuples.
Tuples are faster than lists due to their immutability, making them the perfect choice when you have a collection of items that you want to remain constant throughout your program. They are also commonly used for functions that return multiple values and for packing and unpacking data.
The tuple is one of the four data types in Python. The other three are list, set, and dictionary.
# create a tuple named a.
# creating a tuple Requires '(' and ')'
a=()
print(a)
()
Python# this is a basic look of a tuple
a=(1,2,3,4,5,6,7)
print(a)
(1, 2, 3, 4, 5, 6, 7)
Python# we can store multiple datatypes in tuple
a=('apple',1,True,3.14)
print(a)
('apple', 1, True, 3.14)
Pythonindexes 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
tuplea= (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
reverse -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
tuplea=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
tuplea
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Python# Accessing first element in tuplea
tuplea[0]
0
Python# Accessing third element in tuplea
tuplea[2]
2
PythonReverse indexing with tuples is exactly like lists. It begins with the last item and -1. When we go backwards, it increases like -1, -2, -3, -4 etc.
# access last item from tuple
tuplea[-1]
9
Python# access 2nd last item from tuple.
tuplea[-2]
8
PythonSlicing is a functionality provided for filtering out the wanted and unwanted elements from a tuple. First two arguments are start and stop index. Elements under these indices are chosen, and the rest are filtered. The step’s argument adds another quirk to slicing.
If we provide 1, no item in the range will be skipped. If we provide 2 for steps, 2 will be added to the index per loop. And 1 item in 2 will be skipped.
syntax: tuple_name[start_index : stop_index : steps]
# creating tupleb
tupleb=(10,11,12,13,14,15,16,17,18,19)
# accesing tuple elements as a group
tupleb[:]
(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
Python# accessing tuple from second item.
tupleb[1:]
(11, 12, 13, 14, 15, 16, 17, 18, 19)
Python# acessing tuple till 9th index.
tupleb[:7]
(10, 11, 12, 13, 14, 15, 16)
Python# accessing tuple from 4th index to 7th index
tupleb[4:7]
(14, 15, 16)
Python# acessing tuple from 2 to 9th index.
tupleb[1:9]
(11, 12, 13, 14, 15, 16, 17, 18)
Python# acessing tuple from -5 to 9th index.
tupleb[-5:9]
(15, 16, 17, 18)
Python# acessing tuple from 0 to -5th index.
tupleb[0:-5]
(10, 11, 12, 13, 14)
Python# use steps to filter out list by skipping elements in patterns
# [start:stop:steps]
#
tuplec=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
# Accessing tuple with step 1.
print(tuplec[::1])
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
Python# Accessing tuple with step 2.
print(tuplec[::2])
(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
Python# Accessing tuple with step 2 as 0th index to -1 index.
print(tuplec[0:-1:2])
# Accessing tuple with step 4.
print(tuplec[::4])
(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
(1, 5, 9, 13, 17)
PythonAccessing The items from nested tuples. Before we try to access the tuple, let’s see how the indexing on the nested tuple works.
As you can see above, 0 to M is the index of the main tuple, which gives access to the sub tuples. And 0 to N
will give access to individual elements inside the sub tuple. You can access the tuples by using the following
syntax: matrix[ M_index ][ N_index ]
## Creating a tuple Matrix with python
Ntuple=(
(1,2,3),
(4,5,6),
(7,8,9),
(10,11,12),
(13,14,15)
)
print(Ntuple)
((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12), (13, 14, 15))
Python# Accessing the tuple at 0th index.
print(Ntuple[0])
(1, 2, 3)
Python# Accessing the 0th item from 0th tuple at Ntuple.
print(Ntuple[0][0])
# Accessing the 1 index item from 3 index tuple at Ntuple.
print(Ntuple[3][1])
1
11
PythonTuples are immutable, which means you cannot change, add, or remove items once the tuple is created. However, if the element is itself a mutable data type like a list, you can change its contents:
my_tuple = (4, 2, [6, 5])
# This will cause an error
my_tuple[1] = 10
However, you can change a mutable element
my_tuple[2][0] = 9
print(my_tuple) # Output: (4, 2, [9, 5])
# Deleting a tuple from del.
del gases
objec1,object2,object3,....,objectn=(value1,value2,value3,.....,valuen)
# Creating a furniture
furniture=('table','chair','cupboard')
# Unpacking values in x,y,z
x,y,z=furniture
print(x,y,z)
table chair cupboard
PythonTuples can be difficult to unpack if the number of values in the tuple is large. Creating an excessive number of objects may be difficult. This is where * comes in; you can choose to unpack some values while handling the rest in “*object”.
syntax:
object1,object2,*object=(value1,value2,value3,valu4,......value_n)
# Creating a tuple
furniture=('table','chair','cupboard','footstool','sofa','recliner')
# Unpacking a tuple and use * for remaining items.
item1,item2,item3,*rest=furniture
# Printing unpaacked items.
print(item1,item2,item3)
table chair cupboard
Python# Unpacking the rest of the tuple.
print(rest)
['footstool', 'sofa', 'recliner']
PythonWe can avoid the “too many values to unpack” error by using *.
# Printing furniture.
print(furniture)
# Printing the tuple with for looped index.
for i in range(len(furniture)):
print(furniture[i])
('table', 'chair', 'cupboard', 'footstool', 'sofa', 'recliner')
table
chair
cupboard
footstool
sofa
recliner
Python# Printing the tuple with iterative loop of furniture.
for i in furniture:
print(i)
table
chair
cupboard
footstool
sofa
recliner
Python# Traversing a tuple loop using while.
i=0
while i<len(furniture):
print(furniture[i],end=' ')
i+=1
table chair cupboard footstool sofa recliner
PythonIn the following code, we used a for loop to iterate through the first tuple, unpacking all the tuples contained within it.
# Creating a nested tuple.
furniture_cart=(
('table',9499),
('chair',1999),
('cupboard',30749),
('footstool',5293),
('sofa',19960),
('recliner',17370))
print(furniture_cart)
(('table', 9499), ('chair', 1999), ('cupboard', 30749), ('footstool', 5293), ('sofa', 19960), ('recliner', 17370))
Python# Printing a formatted tuple
for item,price in furniture_cart:
print(f'Name:{item} \t Price:{price}')
Name:table Price:9499
Name:chair Price:1999
Name:cupboard Price:30749
Name:footstool Price:5293
Name:sofa Price:19960
Name:recliner Price:17370
PythonTo join a tuple, use the “+” operator. However, because tuples are immutable, we can only reassign them to a variable. Let’s make a few tuples to demonstrate the examples.
# Creating tuples with quotes and authors.
Quote=("The","best","is","yet","to","be","-")
Author=(" Robert","Browning")# Joining tuples with quotes and author.
Quote1=Quote+Author
print(Quote1)
('The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning')
PythonTo multiply quotes, use the “*” operator followed by a number.
Syntax: tuplename*number
The tuples will be multiplied by a number.
# multiplying Quote1 with 2
Quote1=Quote1*2
print(Quote1)
print(Quote1*2)
('The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning')
('The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning', 'The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning')
PythonLet’s Use Quote1 to demonstrate the methods
all()
returns true if all elements are empty or true if all elements are true.any()
returns False if the tuple is empty; otherwise, True if any element of the tuple is True.len()
returns the tuple’s length.enumerate()
returns an object iteratively from a tuple.max()
returns the largest element of a tuple.min()
Returns the smallest element of a tuple.sum()
adds the numbers in the tuple together.sorted()
takes the elements of a tuple and returns a new sorted list.tuple()
is used to convert an iterable to a tuple.Tuples are a powerful feature of Python, offering a way to create immutable sequences of objects. They play a crucial role in Python programming, particularly in situations where an immutable sequence of heterogeneous data is needed. By understanding and using tuples effectively, you can write more efficient and reliable Python code.
Remember, the journey of mastering Python is filled with learning and exploration. Don’t hesitate to experiment with tuples in your projects and explore more advanced features as you progress. Happy coding!
ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.
What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!
Start using NotebookLM today and embark on a smarter, more efficient learning journey!
This can be a super guide for you to start and excel in your data science career.
Solve this quiz for testing Manova Basics
Test your knowledge on pandas groupby with this quiz
Observe the dataset and try to solve the Visualization quiz on it
To perform ANCOVA (Analysis of Covariance) with a dataset that includes multiple types of variables, you’ll need to ensure your dependent variable is continuous, and you can include categorical variables as factors. Below is an example using the statsmodels library in Python: Mock Dataset Let’s create a dataset with a mix of variable types: Performing…
How useful was this post? Click on a star to rate it! Submit Rating
Complete the code by dragging and dropping the correct functions
Python functions are a vital concept in programming which enables you to group and define a collection of instructions. This makes your code more organized, modular, and easier to understand and maintain. Defining a Function: In Python, you can define a function via the def keyword, followed by the function name, any parameters wrapped in parentheses,…
Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.
Stable Diffusion Models: Where Art and AI Collide Artificial Intelligence meets creativity in the fascinating realm of Stable Diffusion Models. These innovative models take text descriptions and bring them to life in the form of detailed and realistic images. Let’s embark on a journey to understand the magic behind Stable Diffusion in a way that’s…