How to choose between list and tuple in python? What's the difference?

Posted by penguin_powered on Tue, 21 Dec 2021 19:54:32 +0100

Lists and tuple s are two common data structures in Python.

Lists and tuples are an ordered collection that can place any data type.

In most programming languages, the data types of collections must be consistent. In python, elements in the same list or tuple can be of different types.

list=[3,7,'Mar','Feb','Jan'] # The list contains both int and string elements
list
[3, 7, 'Mar', 'Feb', 'Jan']

tup=("hello",2022) #Tuples contain both int and string elements
tup
('hello', 2022)
Copy code

The difference between lists and tuples

  • The list is a variable sequence. We can add, delete or change the elements in the list at will. The length and size are not fixed. Because the list is variable, the list cannot be used as a key in the dictionary.

  • Tuples are immutable sequences with variable length and size. They cannot add, delete or change elements unless they are replaced as a whole. Therefore, they can be used as key s in the dictionary.

As shown in the following code, we can easily modify the list, such as changing Jan to Dec;

list=[3,7,"Mar",'Feb','Jan'] 
list[4]="Dec"  #The index in python also starts from 0, and list[4] indicates Jan, the fifth element of the access list
list
[3, 7, 'Mar', 'Feb', 'Dec']
Copy code

If tuples are modified in the same way, python will report TypeError because tuples are immutable.

tup=("hello",2022)
tup[1]=2012
--------------------------------------------------------------
TypeError  Traceback (most recent call last)
<ipython-input-8-5669ecb45950> in <module>     
 1 tup=("hello",2022)
----> 2 tup[1]=2012
TypeError: 'tuple' object does not support item assignment
 Copy code

However, if you just want to make some "changes" to tuples, you can only re assign values to tuples and create new tuples; Tuples are like words you write with a pen. They can't be erased unless they are rewritten on another piece of paper, and lists are like words written with a pencil. If you write wrong, you can erase and change them.

As shown in the following code, we add an element 2012 to the tuple. In fact, it is equivalent to creating a new tuple and filling in the values of the original two tuples in turn.

tup=("hello",2022)
new_tup=tup + (2012,) # Create a new tuple new_tup, fill in the values of the original tuple in turn
new_tup
('hello', 2022, 2012)
Copy code

Since the list is variable, we just need to add the elements we want to add at the end of the list, as shown in the following code. We just modify the elements of the original list without creating a new list.

list = [1,2,3,'Jan','Feb','Mar']
list.append(4)
list
[1, 2, 3, 'Jan', 'Feb', 'Mar', 4]
Copy code

Through the above code, we have understood the basic differences between lists and tuples. Let's take a look at the operations and precautions of lists and tuples.

Both lists and tuples in Python support negative indexes

The negative index starts from the tail. The index of the penultimate element is - 1, - 2 represents the penultimate element, and so on.

list=[1, 2, 3, 'Jan', 'Feb', 'Mar', 4]
list[-1]
4
tup=('hello', 2022, 2012)
tup[-1]
2012
 Copy code

Both lists and tuples support slicing operations

list=[1, 2, 3, 'Jan', 'Feb', 'Mar', 4]
list[1:3] #Returns a sublist with indexes from 1 to 2 in the list
[2,3]
tup=(1,2,3,4,5)
tup[1:3]#Returns a sublist with indexes from 1 to 2 in a tuple
(2, 3)
Copy code

Lists and tuples can be nested at will

list = [[1, 2, 3],['Jan', 'Feb', 'Mar']]# Each element of a list can be a list
tup=((1,2,3),(4,5)) # Each element of a tuple can also be a tuple
 Copy code

**Both lists and tuples support traversal operations
**

list=[1, 2, 3, 'Jan', 'Feb', 'Mar', 4] 
for i in list:
    print(i)
1
2
3
Jan
Feb
Mar
4
tup=(1,2,3,4,5)
for i in tup:
    print(i)
1
2
3
4
5
 Copy code

Common built-in functions for lists and tuples:

list=[1, 2, 3, 2, 3, 1, 4]
 list.count(1) #count(item) indicates the number of times items appear in the list / tuple
2 #The number 1 appears 2 times in the list
list.index(4) #index(item) indicates the index of the first occurrence of item in the returned list / tuple
6 #The first occurrence of the number 4 in the list is 6
list.reverse() #list.reverse() means to reverse the list and flip the elements back and forth
list
[4, 1, 3, 2, 3, 2, 1]
list.sort()#list.sort() sorts the list from small to large by default
list
[1, 1, 2, 2, 3, 3, 4]
Copy code

**The difference between list and tuple storage
**

list=[1,2,3,4,5,6]
list.__sizeof__() #__ sizeof__ () the size of space allocated by the printing system
88
tup=(1,2,3,4,5,6)
tup.__sizeof__()
72
 Copy code

As can be seen from the above figure, the same elements are placed in the list and tuple, but the storage space of the tuple is 16 bytes less than that of the list, because the list also needs to store pointers to point to the corresponding elements when storing elements. Due to the length of the article, the mechanism of list space allocation will be introduced in another article.

Performance comparison between list and tuple

By understanding the differences between list and tuple storage methods, we can know that tuple is lighter than list, and tuple performance speed is slightly better than list.

Let's look at the time comparison between initialization and index access.

python -m timeit "x=[1,2,3,4,5,6,7,8]"
5000000 loops, best of 5: 55.1 nsec per loop
python -m timeit "x=(1,2,3,4,5,6,7,8)"
20000000 loops, best of 5: 11.5 nsec per loop
 Copy code

Compared with the above initialization time, we can see that the initialization speed of tuples is more than 4 times faster than that of lists.

Index access

python -m timeit -s "x=[1,2,3,4,5,6,7,8]" "y=x[3]"
10000000 loops, best of 5: 29.7 nsec per loop
python -m timeit -s "x=(1,2,3,4,5,6,7,8)" "y=x[3]"
10000000 loops, best of 5: 31.8 nsec per loop
 Copy code

The speed difference of access time between the two is very small. If you want to add, delete or change elements, you'd better choose the list. Because tuples cannot be changed after they are created, tuples are more suitable for scenarios where data and quantity are not changed, such as month name of a year, student achievement, etc; After the list is created, it can be added, deleted, modified and queried. It can be used to store commodity names, website logs and other scenarios.

summary

Lists and tuples are ordered and can store collections of any data type. The differences are as follows:

  • The list is variable in length and size. You can add, delete and query elements at will. The storage space is slightly larger than the tuple, and the performance is slightly weaker than the tuple. It cannot be used as the key of the dictionary

  • Tuples are immutable, fixed in length and size, and cannot be added, deleted or modified. Tuples are faster than list access and processing, and can be used as the key of the dictionary.

Thank you for your reading. Welcome to discuss and learn together.

Topics: Python list