1. Python Tuples vs Lists – Objective
In our previous python tutorials, we’ve seen tuples in python and lists in python. Both are heterogeneous collections of python objects. But which one do you choose when you need to store a collection? To answer this question, we first get a little deeper into the two constructs and then we will study comparison between python tuples vs lists.
2. A Revision of Tuples in Python
Before comparing tuples and lists, we should revise the two. First, we look at a tuple.
A tuple is a collection of values, and we declare it using parentheses. However, we can also use tuple packing to do the same, and unpacking to assign its values to a sequence of variables.
- >>> numbers=(1,2,'three')
- >>> numbers=4,5,6
- >>> a,b,c=numbers
- >>> print(numbers,a,b,c,type(numbers))
-
A tuple is returned when we call the method localtime().
- >>> import time
- >>> time.localtime()
-
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=1, tm_hour=23, tm_min=1, tm_sec=59, tm_wday=0, tm_yday=1, tm_isdst=0)
To access a tuple, we use indexing, which begins at 0.
-
Finally, we can delete an entire tuple.
- >>> del numbers
- >>> numbers
-
We also learned some functions and methods on tuples and lists. You must read our tutorials on them for more insight.
-
3. A Revision of Lists in Python
Unlike in C++, we don’t have arrays to work with in Python. Here, we have a list instead.
We create lists using square brackets.
- >>> colors=['red','blue','green']
-
We can slice lists too.
- >>> colors[-2:]
-
[‘blue’, ‘green’]
-
4. Python tuples vs lists – Mutability
The major difference between tuples and lists is that a list is mutable, whereas a tuple is immutable. This means that a list can be changed, but a tuple cannot.
a. A List is Mutable
Let’s first see lists. Let’s take a new list for exemplar purposes.
- >>> list1=[0,1,2,3,4,5,6,7]
- Now first, we’ll try reassigning an element of a list. Let’s reassign the second element to hold the value 3.
Traceback (most recent call last):
File “<pyshell#40>”, line 1, in <module>
numbers
NameError: name ‘numbers’ is not defined