Showing posts with label Python: Lists vs. Tuples. Show all posts
Showing posts with label Python: Lists vs. Tuples. Show all posts

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