A Beginner’s Guide to Immutable Tuples

Tuples are a sequence of Python objects. A tuple is created by separating items with a comma. They are put inside the parenthesis “”(“” , “”)””.

Topics: ,

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.

What is a Tuple in Python?

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.

Why Use 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.

  • Tuples are also a sequence of Python objects. A tuple is created by separating items with a comma like lists and enclosed within ‘(‘ ‘)’.
  • A single item tuple should use a comma at the end.
  • A tuple is a variable that is similar to a list. It is used to store multiple values in an ordered collection.
  • But tuples are unchangeable, so they are referred to as immutable.
  • Once values are stored (or initialized) in the tuple, they can’t be updated, added, or removed.

1. Create Tuple

Python
Python
Python
# create a tuple named a.
# creating a tuple Requires '(' and ')'
a=()
print(a)
Output
()
Python
Python
Python
Python
# this is a basic look of a tuple
a=(1,2,3,4,5,6,7)
print(a)
Output
(1, 2, 3, 4, 5, 6, 7)
Python
Python
Python
Python
# we can store multiple datatypes in tuple
a=('apple',1,True,3.14)
print(a)
Output
('apple', 1, True, 3.14)
Python

2. Access Tuple Items

  • Indexing in tuple starts with 0.
  • The rest of the details for indexing in tuples is similar to lists.
  • How to access different elements of list.
indexes   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 
  • Indexing in the list starts with 0.
  • Reverse indexing starts with -1 from the end of the list.
  • Take reference of indexing with list to understand in more detail
Python
Python
Python
tuplea=(0,   1,  2,  3,  4,  5,  6,  7,  8,  9)
tuplea
Output
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Python
Python
Python
Python
# Accessing first element in tuplea
tuplea[0]
Output
0
Python
Python
Python
Python
# Accessing third element in tuplea
tuplea[2]
Output
2
Python

Reverse Indexes

Reverse 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.

Python
Python
Python
# access last item from tuple
tuplea[-1]
Output
9
Python
Python
Python
Python
# access 2nd last item from tuple.
tuplea[-2]
Output
8
Python

3. Tuple Slicing

Slicing 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]

Python
Python
Python
# creating tupleb
tupleb=(10,11,12,13,14,15,16,17,18,19)
# accesing tuple elements as a group
tupleb[:]
Output
(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
Python
Python
Python
Python
# accessing tuple from second item.
tupleb[1:]
Output
(11, 12, 13, 14, 15, 16, 17, 18, 19)
Python
Python
Python
Python
# acessing tuple till 9th index.
tupleb[:7]
Output
(10, 11, 12, 13, 14, 15, 16)
Python
Python
Python
Python
# accessing tuple from 4th index to 7th index
tupleb[4:7]
Output
(14, 15, 16)
Python
Python
Python
Python
# acessing tuple from 2 to 9th index.
tupleb[1:9]
Output
(11, 12, 13, 14, 15, 16, 17, 18)
Python
Python
Python
Python
# acessing tuple from -5 to 9th index.
tupleb[-5:9]
Output
(15, 16, 17, 18)
Python
Python
Python
Python
# acessing tuple from 0 to -5th index.
tupleb[0:-5]
Output
(10, 11, 12, 13, 14)
Python
Python
Python
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])
Output
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
Python
Python
Python
Python
# Accessing tuple with step 2.
print(tuplec[::2])
Output
(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
Python
Python
Python
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])
Output

(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)

(1, 5, 9, 13, 17)
Python

4. Nested Tuples

  • Nested tuples are much like lists in structure and behaviour.
  • the only difference is that tuples are unchangeable

Accessing The items from nested tuples. Before we try to access the tuple, let’s see how the indexing on the nested tuple works.

image 167

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 ]

Python
Python
Python
## Creating a tuple Matrix  with python
Ntuple=(
       (1,2,3),
       (4,5,6),
       (7,8,9),
       (10,11,12),
       (13,14,15)
       )
print(Ntuple)
Output
((1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12), (13, 14, 15))
Python
Python
Python
Python
# Accessing the tuple at 0th index.
print(Ntuple[0])
Output
(1, 2, 3)
Python
Python
Python
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])
Output
1

11
Python

5. Immutability of Tuples

Tuples 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:

Python
Python
Python
my_tuple = (4, 2, [6, 5])

# This will cause an error
my_tuple[1] = 10  

However, you can change a mutable element

Python
Python
Python
my_tuple[2][0] = 9  
print(my_tuple)  # Output: (4, 2, [9, 5])

Delete a Tuple

Python
Python
Python
# Deleting a tuple from del.
del gases

6. Duplicate Unpacking

  • Tuples can be unpacked using the syntax below.objec1,object2,object3,....,objectn=(value1,value2,value3,.....,valuen)
  • Keep in mind that the number of objects you unpack into must equal the number of values in the tuple.
Python
Python
Python
# Creating a furniture
furniture=('table','chair','cupboard')
# Unpacking values in x,y,z
x,y,z=furniture
print(x,y,z)
Output
table chair cupboard
Python

Unpacking tuples with ‘*’

Tuples 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)

Python
Python
Python
# 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)

Output
table chair cupboard
Python
Python
Python
Python
# Unpacking the rest of the tuple.
print(rest)
Output
['footstool', 'sofa', 'recliner']
Python

We can avoid the “too many values to unpack” error by using *.

7. Move Through a Tuple

  • Iterate a Tuple using a for loop iterate with index.
    • This is useful for loop traversal.
  • The while loop

Iterate through the tuple using index.

Python
Python
Python
# Printing furniture.
print(furniture)

# Printing the tuple with for looped index.
for i in range(len(furniture)):
    print(furniture[i])
Output

('table', 'chair', 'cupboard', 'footstool', 'sofa', 'recliner')

table
chair
cupboard
footstool
sofa
recliner
Python

loop traversal within operator.

Python
Python
Python
# Printing the tuple with iterative loop of furniture.
for i in furniture:
    print(i)
Output
table
chair
cupboard
footstool
sofa
recliner
Python

While loop traversal.

Python
Python
Python
# Traversing a tuple loop using while.
i=0
while i<len(furniture):
    print(furniture[i],end='  ')
    i+=1
Output
table  chair  cupboard  footstool  sofa  recliner  
Python

8. Iterate through nested tuples

In the following code, we used a for loop to iterate through the first tuple, unpacking all the tuples contained within it.

Python
Python
Python
# Creating a nested tuple.
furniture_cart=(
    ('table',9499),
    ('chair',1999),
    ('cupboard',30749),
    ('footstool',5293),
    ('sofa',19960),
    ('recliner',17370))
print(furniture_cart)
Output
(('table', 9499), ('chair', 1999), ('cupboard', 30749), ('footstool', 5293), ('sofa', 19960), ('recliner', 17370))
Python
Python
Python
Python
# Printing a formatted tuple 
for item,price in furniture_cart:
    print(f'Name:{item} \t Price:{price}') 
Output
Name:table 	 Price:9499
Name:chair 	 Price:1999
Name:cupboard 	 Price:30749
Name:footstool 	 Price:5293
Name:sofa 	 Price:19960
Name:recliner 	 Price:17370
Python

Operations on Tuples

  • Combine Two Tuples
  • Multiplying Tuples

Connect Two Tuples.

To 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.

Python
Python
Python
# 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)
Output
('The', 'best', 'is', 'yet', 'to', 'be', '-', ' Robert', 'Browning')
Python

Tuples Multiplication

To multiply quotes, use the “*” operator followed by a number.

Syntax: tuplename*number

The tuples will be multiplied by a number.

Python
Python
Python
# multiplying  Quote1 with 2
Quote1=Quote1*2
print(Quote1)
print(Quote1*2)
Output
('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')
Python

9. Tuple In Built Methods

  • count()
  • index()

Let’s Use Quote1 to demonstrate the methods

10. Integrated Functions

  • These functions are generic in nature.
  • They can be used on iterable data types.
  • 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.

Conclusion

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!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

  • ANCOVA: Analysis of Covariance with python

    ANCOVA is an extension of ANOVA (Analysis of Variance) that combines blocks of regression analysis and ANOVA. Which makes it Analysis of Covariance.

  • Learn Python The Fun Way

    What if we learn topics in a desirable way!! What if we learn to write Python codes from gamers data !!

  • Meet the most efficient and intelligent AI assistant : NotebookLM

    Start using NotebookLM today and embark on a smarter, more efficient learning journey!

  • Break the ice

    This can be a super guide for you to start and excel in your data science career.

  • Hypothesis Testing: A Comprehensive Overview

    This article delves into the application of hypothesis testing across diverse domains

  • Versions of ANCOVA (Analysis Of Covariance) with python

    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…

  • Python Variables

    How useful was this post? Click on a star to rate it! Submit Rating Average rating 0 / 5. Vote count: 0 No votes so far! Be the first to rate this post.

  • A/B Testing Quiz

    Complete the code by dragging and dropping the correct functions

  • Python 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,…

  • Python Indexing: A Guide for Data Science Beginners

    Mastering indexing will significantly boost your data manipulation and analysis skills, a crucial step in your data science journey.

  • Diffusion Models: Making AI Creativity

    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…

  • Quiz Challenge: Basics with Python [Questions]

    Solve These Questions in Following Challange

  • Introducing Plethora of Stable Diffusion models: Part 1

    Generate AI images as good as DALL-E completely offline.

Instagram
WhatsApp
error: Content is protected !!