The difference between lists and tuples in python

  • 2020-06-15 09:46:00
  • OfStack

If you know about lists and tuples in python, you probably know that tuples are immutable relative to lists, meaning that data in tuples cannot be changed at will. Apart from the fact that lists are bracketed and tuples are bracketed, these two data types don't seem to be different, and are used to hold 1 series of data. Is this really the case?


a = [1, 3, 5, 7, 'a']
b = (1, 3, 5, 7, 'b')
#  Now change b The values in the 
b[2] = 4

TypeError                 Traceback (most recent call last)
<ipython-input-2-96f3d2fefb53> in <module>()
   4 
   5 #  Now change b The value of the data in 
----> 6 b[2] = 4
TypeError: 'tuple' object does not support item assignment

It seems that besides tuples being immutable, lists can replace tuples entirely, so why create tuples? In fact, there is a deeper meaning behind this. Lists are used to represent 1 group of data of the same type (same value), while tuples are used to store data of different types (different values). In short, lists are homogeneous while tuples are heterogeneous.

So let's say I have a book, and I have some annotations in it. We use tuples to represent lines on pages in the book, like position = (page, line), and then put it in the dictionary as a comment key to indicate lines on pages with annotations. At the same time, we represent these locations in a list, and if there are new locations, we can add them to the list. This is consistent with the fact that lists can change data. But it doesn't make sense to change the data in the tuple, because the coordinates already exist.

In the module of python, we can find many examples:


range(10)

range(0, 10)

For example, range method is used to generate 1 column of ordered data. These data are equivalent and have no different functions, so it is most appropriate to use list to represent. Instead, take the following example:


from datetime import datetime
datetime.now()

datetime.datetime(2017, 12, 17, 20, 23, 13, 578752)

The current time is a good time to table in terms of tuples, where each data has a different function, or value, like the first data for the year.

Speaking of which, it reminds us of the named tuple nametuple, which is used to quickly generate a class. It can be seen as a lightweight alternative to classes and fits well with the functions of tuples mentioned above.


Related articles: