Python: List Vs Tuple

 The aim of this tutorial is to state the differences between lists and tuples and how to manage these two data structures.

Lists and Tuples are types of data structures that hold one or more than one objects or items in a predefined order. We can contain objects of any data type in a list or tuple, including the null data type defined by the 'None' keyword.

What is a List?

In other programming languages, list objects are declared similarly to arrays. Lists don't have to be homogeneous all the time, so they can simultaneously store items of different data types. This makes lists the most useful tool. The list is a kind of container data structure of Python that is used to hold numerous pieces of data simultaneously. Lists are helpful when we need to iterate over some elements and keep hold of the items.

What is a Tuple?

A tuple is another data structure to store the collection of items of many data types, but unlike mutable lists, tuples are immutable. A tuple, in another words, is a collection of items separated by commas. Because of its static structure, the tuple is more efficient than the list.

Differences between Lists and Tuples

In most cases, lists and tuples are equivalent. However, there are some important differences to be explored here.

Syntax Differences

The syntax of a list differs from that of tuple. Items of a tuple are enclosed by parantheses or curved brackets (), whereas items of a list are enclosed by square brackets [].

Example Code:

#Python program to show the differences between creating a list and a tuple
list_=[5, 3, 7, 9, 1]
tuple_=(2, 4, 6, 8, 12)

print("List is:", list_)
print("Tuple is:", tuple_)

Output:

List is: [5, 3, 7, 9, 1]
Tuple is: (2, 4, 6, 8, 12)

In above example, we have declared both list and tuple. Both have certain numbers of entegers, but list is enclosed by [] (square brackets) whereas tuple is enclosed by () (curly brackets). We can find out the data type whether it is list or tuple, by type() method.

Example Code:

#Python program to show the data type of a data structure
list_=[5, 3, 7, 9, 1]
tuple_=(2, 4, 6, 8, 12)

print(type(list_))
print(type(tuple_))

Output:

<class 'List'>
<class 'Tuple'>

Mutable Vs. Imutable (List Vs. Tuple)
An important difference between a list and a tuple is that a List is mutable whereas a Tuple is immutable. Means, a List's items  can be easily modified or changed whereas a Tuple's items cannot be modified or changed.

As a List is a mutable data type so it cannot be employed as key of dictionary. Because a key of a Python dictionary is an immutable object. So Tuples can be used as keys to a dictionary, if required.

The following code example will show the mutable and immutable nature of a list and a tuple:

#creating a list and a tuple
list_=[5, 3, 7, 9, 1]
tuple_=(2, 4, 6, 8, 12)

#modifying the last integer in both data types
print(list_)
list_[4]=100
print(list_)

print(tuple_)
try:
    tuple_[4]=20
    print(tuple_)
except TypeError:
 print("Tuples cannot be modified because they are immutable")

Output:

[5, 3, 7, 9, 1]
[5, 3, 7, 9, 100]
(2, 4, 6, 8, 12)
Tuples cannot be modified because they are immutable.

Here, we can easily notice that when we tried to change the last element of a list, it is changed (from 1 to 100), but when we tried to change the last element of a tuple (from 12 to 20) in a try block, it raised an error. We got output from except block. This is because tuples are immutable.

Size difference:
Since tuples are immutable, Python allocates bigger chunks of memory with minimal overhead. Python on the contrary, allots smaller memory chunks for lists. The tuple would therefore have less memory than the list. If we have a huge number of items, this makes tuples a little more memory efficient than lists.
In the following example, we will create a list and a tuple with identical items and compare their sizes:

#code to show differences in size of a list and a tuple
#creating a list and a tuple
list_=["Tuple", "List", "Python", "Differences"]
tuple_=("Tuple", "List", "Python", "Differences")

#printing sizes
print("Size of Tuple:", tuple_.__sizeof__())
print("Size of List:", list_.__sizeof__())

Output:

Size of Tuple: 56
Size of List: 72

Available Functions:
Tuples have fewer built in functions than lists. We may leverage the in-built function dir([object) to access all the corresponding methods for the list and tuple.

Examples
To print directory of a list
list_=["Tuple", "List", "Python", "Differences"]
#printing directory of list
dir(list_)

Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

To print directory of a tuple:

tuple_=["Tuple", "List", "Python", "Differences"]
#printing directory of list
print(dir(tuple_),end=",")

Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Tuples and Lists: Key similarities
  • They both hold collection of items and are heterogeneous data types, means they can contain multiple data types simultaneously.
  • They're both ordered, which implies the items or objects are maintained in the same order as they were placed until changed manually.
  • Because they're both sequential data structures, we can iterate through the objects they hold, hence they are iterables.
  • An integer index, enclosed in square brackets[index], can be used to access objects of both data types.

Python: Tuple

 In Python, a tuple is one of the data types that holds the sequence of items. All the items or elements are separated from each other by comma (,) and enclosed in paranthesis(). Although the parentheses are not required, they are recommended.

Features of Python Tuple:

  • Tuples are an immutable data type, meaning their elements cannot be changed after they are formed.
  • Each element in a tuple has a specific order, that will be never changed because tuples are ordered sequences.
Forming a Tuple:
Any number of items, including those with various data types dictionary, string, float, list etc can be contained in a tuple.

Code:

#Python program to show how to create a tuple
#Creating an empty tuple
empty_tuple=()
print("empty tuple:", empty_tuple)

#Creating tuple having integers
int_tuple=(2, 4, 6, 8, 10)
print("tuple with integers:", int_tuple)

#Creating a tuple having objects of different data types
mixed_tuple=(2, "Python", 6.8, 10)
print("tuple with different data types:", mixed_tuple)

#Creating a nested tuple 
nested_tuple=("Python", {6:8, 9:8, 5:2}, (3, 5, 7))
print("A nested tuple:", nested_tuple)


Output:

empty tuple: ()
tuple with integers: (2, 4, 6, 8, 10)
tuple with different data types: (2, "Python", 6.8, 10)
A nested tuple: 
("Python", {6:8, 9:8, 5:2}, (3, 5, 7))

Parentheses are not necessary for the construction of multiples. This is known as tripple pressing.

Code:

#Python program to create a tuple without using parentheses
#Creating the tuple
tuple_=4.2, "Python", ["Lists", "tuples"]
#displaying the tuple 
print(tuple_)
#checking the data type of object tuple_
print(type(tuple_))
#trying to modify the tuple_
try:
    tuple[1]=4.5
except:
    print(TypeError)


Output:

(4.2, "Python", ["Lists", "tuples"])
<class 'tuple'>
<class 'TypeError'>
 Here, some elements are not in brackets, however elements must be seperated by comma(,) to recognize the tuple.

We can verify the above statement by following code: 

Code:

#Python program to show how to create a tuple having single element
#when we don't use comma(,)
tuple_single=("Python")
print(type(tuple_single))

#using of comma(,)
tuple_single=("Python",)
print(type(tuple_single))

#missing of brackets
tuple_single="Python",
print(type(tuple_single))


Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

It is proved by above code that bracket is not but comma(,) is necessary to make a tuple.

Accessing Tuple Elements
A tuple's object can be accessed in a variety of ways:

1. Indexing:
We can use the index operator [] to access an object in a tuple, where the index starts at zero (0). If a tuple has five elements, the index will denote these 0 to 4 respectively. If we try to get the element that is outside the scope like index[5], we get an error message. 
Let's see the above statements in programming:

Code:

#Python program to show indexing.
tup=(5, 7, 6, 8, 9)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[4])
print(tup[5])


Output:

5
7
6
9
IndexError: tuple index out of range

We cannot provide an index of a floating data type. It only works with integers or slices. If we provide a floating index, the result will be TypeError.

Code:

#Python program to show indexing with float.
tup=(5, 7, 6, 8, 9)
print(tup[1.0])


Output:

IndexError: tuple indices must be integers or slices, not float.

Nested Tuple:
In nested tuple the indexing is done by two numbers, First number indicates the tuples, it also starts from zero(0) and second number indicates the element of that particular tuple, it also starts from zero(0).
Let's understand it by codes:

Code:

#Python program to show indexing in nested tuples.
tup_nested=("Pythpn", [4, 3, 2, 1], (5, 7, 6, 8, 9))
print(tup_nested[0][2])
print(tup_nested[1][0])
print(tup_nested[2][4])


Output:

t
4
9

Negative Indexing:
Python tuple supports negative indexing too. It starts from -1 and it indicates the rightmost element of the tuple. -2 indicates the second last and so on.
Let's try it 

Code:

#Python program to show negative indexing in  tuple.
tup_negInd=("orange", "apple", "banana", "mango")
print(tup_negInd[-1])
print(tup_negInd[-3])
print(tup_negInd[-4:-1])


Output:

mango
apple
('orange', 'apple', 'banana')

Slicing:
Slicing is a comman practice in Python and the most comman way for programmers to deal with practical issues.By slicing in Python tuple, we can get only some sequential elements or a part of the tuple which is required.
Let's understand it by codes:

Code:

#Python program to show slicing in Python tuples.
tup_slicing=("orange", "apple", "banana", "mango", "lemon", "papaya")
#to see only first four elements
print(tup_slicing[0:4])
#to see the elements between 2nd and 5th elements
print(tup_slicing[2:5])
#to see the entire tuple
print(tup_slicing[:])


Output:

('orange', 'apple', 'banana', 'mango')
('banana', 'mango', 'lemon')
('orange', 'apple', 'banana', 'mango', 'lemon', 'papaya')

Deleting a Tuple:
As discussed earlier, a tuple's element cannot be modified or removed but we can remove entire tuple by del keyword.

Code:

#Python program to delete a Python tuple.
tup_=("orange", "apple", "banana", "mango", "lemon", "papaya")
print(tup_)
# try to delete only one element
print(del[2])
#to delete entire tuple
del(tup_)
print(tup_)


Output:

('orange', 'apple', 'banana', 'mango', 'lemon', 'papaya')
SyntaxError: invalid syntax
name 'tup_' is not defined

In above output, we tried to delete the 2nd element of the tuple by syntax del[2], but it is recognised as invalid syntax by Python. whereas when we deleted the entire tuple by syntax del(tup_), the tuple is deleted and then we tried to print the tuple, but now it doesnot exist, so the message appears name'tup_' is not defined.

Repeat Tuples in Python:
We can repeat the elements of the  tuple as following example:

Code:

#Python program to show repetition in Python
tup_=("orange", "apple")
print("The original tuple is :", tup_)
# repeting the tuple's element
tup_= tup_*3
print("New tuple is :", tup_)


Output:

The original tuple is : ('orange', 'apple')
New tuple is : ('orange', 'apple', 'orange', 'apple', 'orange', 'apple')

Tuple Methods:
Count() and Indez() methods in Python:
We all know Python tuple is a collection of immutable objects. However there are some ways to work with tuples in Python. These are count() and Index () methods, which are explained here by some examples.

Count() method:

The times the predetermined component happens in the tuple is returned by the count() capability of the Tuple.

Code:

#creating tuples
tup_1=(0, 1, 4, 3, 2, 3, 2, 4, 1, 3, 4, 2)
tup_2=("orange", "apple", "banana", "apple", "orange", "papaya")
# counting the appearance of 2 in tup_1
res= tup_1.count(2)
print("Count of 2 in tup_1:", res)
# counting the appearance of orange in tup_2
res= tup_2.count('orange')
print("Count of orange in tup_2:", res)


Output:

Count of 2 in tup_1: 3
Count of orange in tup_2: 2

Index() Method:
The index() function returns the first instance of the requested element from the Tuple.

Parameters: 
  • The thing that must be looked for.
  • Start: (Optional) the index is used to begin the final (optional) search: the most recent index from which the search is carried out.
  • Index Method
Code:

#creating tuples
tup_1=(0, 1, 4, 3, 2, 3, 2, 4, 1, 3, 4, 2)
#getting the index of 3
res =  tup_1.index(3)
print("first occurance of 3 is:", res)
# getting the index of 3 after 4th index
res= tup_1.index(3, 4)
print("first occurance of 3 after 4th index is:", res)

Output:

first occurance of 3 is: 3
first occurance of 3 after 4th index is: 5

Tuple Membership Test:
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.

Code:

#Python progrm to show how to perform membership test for tuples.
#creating a tuple
tup_=("orange", "apple", "banana", "apple", "orange", "papaya")
#in operator
print('apple' in tup_)
print('tomato' in tup_)
#not in operator
print('potato' not in tup_)
print('orange' not in tup_)

Output:

True
False
True
False

Iterating Through a Tuple

A for loop can be used to iterate through each tuple element.

Code:

#Python progrm to show how to iterate over tuple elements
#creating a tuple
tup_=("orange", "apple", "banana", "apple", "orange", "papaya")
#iterating over tuple elements using a for loop
for item in tup_:
    print(item)

Output:

orange
apple
banana
apple
orange
papaya

Changing a Tuple:
Tuples, instead of records, are permanent articles.
This suggests that once the elements of a Tuple have been defined, we cannot change them. However the nested elements can be altered if the element itself is a chargeable data type like a list.

Multiple values can be assigned to a Tuple through reassignment.

Code:

#Python progrm to show that Python tuples are immutable objects.
#creating a tuple
tup_=("orange", "apple", "banana", "apple", [1, 2, 3, 4])
#trying to change the element at index 2
try:
    tup_[2] = "items"
    print(tup_)
except Exception as e:
    print(e)
#but inside a tuple, we can change elements of a mutable object
tup_[-1][2] = 10
print(tup_)
#changing the whole tuple
tup_=(
"orange", "apple")
print(tup_)

Output:

'tuple' object doesn't support item assignment
('orange', 'apple', 'banana', 'apple', [1, 2, 3, 4])
('orange', 'apple')

The + operator can be used to combine multiple tuples into one. This phenomenon is known as concatenation.
We can also repeat the elements of a tuple a predetermined number of times by using the * operator. This is already demonstrated above.
The aftereffects of tasks + and * are new tuples.

Code:

#Python progrm to show how to concatenate tuples.
#creating a tuple
tup_=("orange", "apple", "banana", "apple")
#adding a tuple to the tup_
print(tup_ + (1, 2, 3))

Output:

('orange', 'apple', 'banana', 'apple', 1, 2, 3)

Tuples have the following advantages over lists:
  • Tuples take less time than lists do.
  • Due to tuples, the code is protected from accidental modifications. It is desirable to store non-changing information in "tuples" instead of "records" if a program expects it.
  • A tuple can be used as a dictionary key if it contains immutable values like strings, numbers, or another tuple. "Lists" cannot be utilized as dictionary keys because they are mutable. 

Python: Functions