Python Tuples vs Lists ? Comparison Between Lists and Tuples

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.

  1. >>> numbers=(1,2,'three')
  2. >>> numbers=4,5,6
  3. >>> a,b,c=numbers
  4. >>> print(numbers,a,b,c,type(numbers))
  5. A tuple is returned when we call the method localtime().

  6. >>> import time
  7. >>> time.localtime()
  8. 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.

  9. Finally, we can delete an entire tuple.

  10. >>> del numbers
  11. >>> numbers
  12. We also learned some functions and methods on tuples and lists. You must read our tutorials on them for more insight.

  13. 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.

  14. >>> colors=['red','blue','green']
  15. We can slice lists too.

  16. >>> colors[-2:]
  17. [‘blue’, ‘green’]

  18. 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.

  19. >>> 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

Posted on by