Python Tuples


  Machine Learning in Python

Summary : Think of a tuple as a snippet of immutable data. They are typically used to represent short sets of data that can either be set as global immutable variables to be used further downstream. However, they are not used to create complex data structures like lists or large datasets like sets.

Contents

 What are Tuples

Think of a tuple as a snippet of immutable data. For example, here is a snippet that represents Brad Pitt.

Create Tuple
Create Tuple
person_1 = ("Brad Pitt", 55, "Los Angeles")
person_2 = ("Angelina Jolie", 45, "Beverly Hills")
Tuple Single Element
Tuple Single Element

Creating a tuple with only 1 element is a bit tricky. You would have to use an extra comma. For example, this would be a string, not a tuple

 tuple_1 = ("Brad Pitt")
 type(tuple_1)
str

However, this would be a tuple. 

 tuple_2 = ("Brad Pitt",)
 type(tuple_2)

tuple

The reason why this happens is because, parenthesis can be used to define precedence. So, to define a tuple with a single element, you have to use an additional comma. You can even define a tuple without the paranthesis.

Tuple without the paranthesis.
Tuple without the paranthesis.
 person_1 = "Brad Pitt", 55 , "Los Angeles"
 person_1
('Brad Pitt', 55, 'Los Angeles')
type(person_1)
tuple

You can even convert a List to a Tuple

Create Tuple from List
Create Tuple from List
 person_list = ["Brad Pitt",55,"Los Angeles"]
 person_tuple = tuple(person_list)
 person_tuple

('Brad Pitt', 55, 'Los Angeles')

 Access Tuple Elements

Just like a List, you can access members of the tuple using indices.

 name_1 = person_1[0]
 name_1
'Brad Pitt'

Or using slices

 person_1[0:2]
('Brad Pitt', 55)

Or using negative indexing

person_1[-3]
'Brad Pitt'
 

 Modify Tuple Elements

However, unlike a list, you cannot change it’s values. For example, this is an illegal operation.. Remember, tuples are immutable

person_1[0] = "Sean Penn"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-654366a6f906> in <module>
----> 1 person_1[0] = "Sean Penn"
TypeError: 'tuple' object does not support item assignment
 

However, if the elements of a tuple are mutable, they can be changed . For example, these lists themselves cannot be changed, but their elements can be.

cast = (["Brad Pitt",55,"Los Angeles"],["Angelina Jolie",45,"Beverly Hills"])
 cast[0][0] = "Tom Cruise"
 cast[0][1] = 56
 cast
(['Tom Cruise', 56, 'Los Angeles'], ['Angelina Jolie', 45, 'Beverly Hills'])

 Advantages of Tuples over Lists

  • Tuples are immutable. So, iterating over a tuple in a loop is much more efficient than lists.
  • Tuples are write-protected. So, python guarantees that any code that uses this tuple will not be able to change it. So, you can use it for holding data that is constant and global in nature

 Tuple Methods

Since tuples are immutable, there are very few in-built methods to it. 

count

count ( ) returns the number of occurrences of an elements in the tuple.

Tuple Count
Tuple Count
 ages = (4,5,7,3,4,7,8,5,8,5)
 ages.count(7)

2

 index

index ( ) returns the first index of the occurrence of an element in the tuple

Tuple Index
Tuple Index
 ages = (4,5,7,3,4,7,8,5,8,5)
 ages.index(7)
2

 Other built-in functions

Other built-in functions in Python that works on other iterables (like lists) work on tuples as well. For example,

  • len ( )
  • min ( )
  • max ( )
  • del ( )
  • sum ( )
  • filter ( )

etc 

length

len ( )Length of a Tuple.

Vowels
Vowels
vowels = ('a','e','i','o','u') 
len(vowels)
5

 min & max

Find out the maximum and minimum values of a tuple . In the following example, alphabetic sorting is done to get the min or max.

Tuple Max
Tuple Max
android_versions = ( "Gingerbread","Honeycomb","Icecream Sandwhich","Cupcake", "Donut", "Eclair", "Froyo",
                    "Jellybean", "Kitkat", "Lollypop","Marshmallow", "Nougat","Oreo","Pie")

 max(android_versions)

'pie'

Similarly, use the min ( ) function to get the minimum value in the tuple.

Tuple Min
Tuple Min
min(android_versions)
'Cupcake'

 delete

del ( ) deletes a tuple.

Tuple Delete
Tuple Delete
del(android_versions)

 sum

sum ( ) adds up all the numbers in the tuple

 ages = (4,5,7,3,4,7,8,5,8,5)
 sum(ages)
56

 filter

filter ( ) also works on tuple.

Filter
Filter
ages = (4,5,7,3,4,7,8,5,8,5)

# Primary schools admist students from 5 to 11
def primary_schools ( age ) :
    if 11 >= age >= 5 :
        return True
    else :
        return False

primary_school_age = filter(primary_schools, ages)

for age in primary_school_age :
    print ( age )

Output

5
7
7
8
5
8
5

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.