Tuples in Python Programming

Tuples in python

Tuples in Python, also known as immutable lists, are ordered sequences of items. Like lists, tuples are made up of items separated by commas. However, unlike the lists, items are enclosed in parentheses instead of square brackets.

The example below shows how to create a list in Python:


numbers = (1,2,3)

The parenthesis is optional but it’s a good practice to have them. When we get to the section about unpacking tuples you will understand why the parenthesis is optional.


numbers = 1,2,3

print(numbers)

#output

#(1, 2, 3)

To create an empty tuple, use the syntax below:


nums = ()

To create a tuple with one element, including a trailing comma after the single element in the tuple.


nums = (1) #without the trailing comma

print(nums) 

#output
#1
nums = (1,) #with the trailing comma

print(nums)

#output
#(1,)

Without the trailing comma, you will end up not creating a tuple, but rather assigning a variable num, to the value enclosed in the parenthesis.

Accessing data items in a tuple

Just like the lists, items in the tuple be accessed by their positions or indexes.

Tuples allow indexing and slicing operations like lists but on the contrary, the items cannot be modified or deleted as tuples are immutable.

The examples below show how to access the individual items in a tuple as well as a group of items in a tuple.


fruits = ('orange', 'mango', 'grape')

print(fruits[1])

print(fruits[2])

print(fruits[0:2])

fruit = fruits[1]

print(fruit)

#outputs

#mango

#grape

#('orange', 'mango')

#mango

Since tuples are immutable, trying to change the values of items in a tuple will result in an error.

Here is the outcome of trying to modify one of the elements in a tuple.


fruit[1] = 'pawpaw'

#Traceback (most recent call last):

#File "ex.py", line 12

#fruit[1] = 'pawpaw'

#TypeError: 'str' object does not support item assignment

As you have seen, you can access elements in a list but altering or modifying the values of the elements is not allowed.

This concept of not being able to modify or reassign items in a tuple is make tuples immutable. In other words, items in a tuple can neither be updated nor deleted.

Operations on tuples

Apart from indexing and slicing operations, there are various other operations that can be performed on a tuple. Let’s take a look at them one after another.

Concatenation

This is an operation involving the combination or joining of one or more sequences to get another one. You can easily add two or more tuples to get another tuple using the addition (+) operator, which in this case does concatenation.


tuple1 = (1,2,3)

tuple2 = (4, 5,6)

print(tuple1 + tuple2)

#output

#(1, 2, 3, 4, 5, 6)

Repetition

This involves repeating a tuple a given number of times. The  multiplication (*) operator is used and in this case, it performs repetition as shown below:


T = (1, 2, 3, 4, 5, 6)

#repeat 2 times

print(T*2)

#repeat 5 times

print(T*5)

#output

#(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)

#(1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)

Membership

Like every other sequence, you can determine whether an item is in a tuple or not using the membership operator in.

If the item in question is available, it will return True, otherwise, it will return False.

Now, let’s demonstrate how to use the membership operator in a tuple to check if a given element is present or not.


T = ('red', 'blue', 'green', 'purple', 'white', 'cyan', 'black')

color = 'yellow'

print(color in T)

color = 'cyan'

print(color in T)

#output

#False

#True

Iteration

Iteration is simply the repetition of a process or action. In a sequence, iteration is the process of going through elements in a sequence in an orderly manner and one of the easiest ways of iterating a sequence is through loops.

Tuples allow iteration and the example below uses the for loop to iterate over all the elements of a tuple.


T = (1,2,3,4,5)

for item in T:

print(item)

#outcome

#1

#2

#3

#4

#5

Packing and unpacking tuples

Packing of a tuple is a term used to describe the creation of a tuple by assigning values separated by commas to a variable without using the parenthesis. For instance:

T = 1,2,3,4,5

This is the same thing as:

T = (1,2,3,4,5)

Hence, creating a tuple is the same thing as packing tuples.

Unpacking a tuple assigns variables to the individual elements or items in a tuple, usually in a single line. It is a way of assigning the items in a tuple to variables separated by commas.

T = (1,2,3)

num1, num2, num3 = T

print(num1)

print(num2)

print(num3)

#output

#1

#2

#3

You are allowed to unpack a tuple with a given number of items into variables corresponding to the total number of items in the tuple. This means that the number of variables must match the number of items in the tuple.

Unpacking if the number of items in the list is more than the variables

Unpacking requires that the number of variables matches the number of items in the tuple, if not, you will get an error.

However, using the starred variable allows you to unpack a variable if the number of variables is less than the number of items in the tuple.


T = (1,2,3)

num1, *num2 = T

print(num1)

print(num2)

#output

#1

#[2, 3]

In the above example, the variable num1 is assigned to 1 and the starred variable num2 takes the rest of the items in the tuple. However, if num1 is starred, then num2 becomes assigned to the last item on the tuple and num1 takes the rest of the items.


T = (1,2,3)

*num1, num2 = T

print(num1)

print(num2)

#output

#[1, 2]

#3

Unpacking in a function call

Unpacking is also done by prefixing a star on a function argument. For example:


def sum(*args):

    total = 0

    for num in args:

        total = total + num

    return total

T = (1,2,3,4,5)

print(sum(*T))

#output

#15

However, if you did not unpack the args variable (parameter), you will get an error.


def sum(args):

    total = 0

    for num in args:

        total = total + num

    return total

T = (1,2,3,4,5)

print(sum(*T))

#Traceback (most recent call last):

#File "/ex.py", line 11, in <module>

#print(sum(*T))

#TypeError: sum() takes 1 positional argument but 5 were given.

Also, if you did not unpack the tuple T, it will treat the tuple as a single entity – a tuple. So, calling on the function sum with the tuple as an argument will not work.


def sum(*args):

    total = 0

    for num in args:

        total = total + num

    return total

T = (1,2,3,4,5)

print(sum(T))

#output

#Traceback (most recent call last):

#File "/ex.py", line 11, in <module>

#print(sum(T))

#File "/ex.py", line 4, in sum

#total = total + num

#TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

Dummy variable

You can use the dummy variable in unpacking when you’re interested in certain items of the tuple.

The dummy variable is used as a placeholder for items in the tuple that you’re not interested in. For example:


_,a,b = (1,2,3)

print(a)

_,a,b,_ = (1,2,3,4)

print(a)

print(b)

#output

#2

#2

#3

Built-in functions for tuples

Len

The len function is used to determine the length or number of items in a tuple.


T1 = (1,2,3)

T2 = ('green', 'yellow', 'blue', 'red', 'purple')

print(len(T1))

print(len(T2))

#output

#3

#5

Count

The count function is used to determine the number of a given item in a list. For instance, to determine the number of the item – (2) in a tuple, the count function is used. The syntax is as follows:


num = (1,2,3,4,4,3,1,2,5,7,2,5,2,1)

print(num.count(1))

print(num.count(2))

print(num.count(4))

#output

#3

#4

#2

Min and Max

The min and max functions are used to determine the smallest or largest item in a tuple.


L = (1,2,3,4,4,3,1,2,5,7,2,5,2,1)

min_value = min(L)

max_value = max(L)

print(min_value)

print(max_value)

#output

#1

#7

Tuple

The tuple function is used to convert a sequence into a tuple. The examples below use the tuple function to convert a string and a list into tuples.


str_value = 'hello'

list_value = ['orange', 'banana', 'grape']

print(tuple(str_value))

print(tuple(list_value))

#output

#('h', 'e', 'l', 'l', 'o')

#('orange', 'banana', 'grape')

Index

This function is used to determine the position or index of the first occurrence of a given item in a tuple.


L = (1,2,3,4,4,3,1,2,5,7,2,5,2,1)

print(L.index(1))

print(L.index(2))

print(L.index(3))

print(L.index(7))

#output

#0

#1

#2

#9

Differences between tuples and lists

Lists and tuples are very powerful data structures in Python. As much as they share a lot in common, however, there are some peculiarities. Here are highlights of some of the differences between tuples and lists.

List Tuple
Mutable Immutable
Items are enclosed in a square bracket Items are enclosed in a parenthesis
Can be sorted Cannot be sorted
Consumes more memory Consumes less memory
Represents a field Represents a record or row

 

Named Tuples

Namedtuple is a special kind of tuple that makes it possible to create immutable sequences that can be accessed based on their field names and dot notations.

It’s a factory function located in the collections module of Python. This makes to code easier to read.

Instead of using indexes, field names are used to access the values in the sequence.


numbers = namedtuple('number', ['a', 'b', 'c'])

even = numbers(2,4,6)

print(even)

#output - number(a=2, b=4, c=6)

for i in even:

    print(i)

#outputs

#2

#4

print(even.a)

print(even.b)

print(even.c)

print(even[2])

#outputs

#2

#4

#6

#6

Leave a Reply

Your email address will not be published. Required fields are marked *