Python learning history - review of basic operations of tuples

Before learning about tuples, let's look back at the articles we wrote before and look at some basic operations of lists:

An Introduction to Lists in Python

Record my Python learning process - the basic operation of the list ,

Here's a quick recap of some key points about tuples:

Lists are mutable sequences, while tuples and strings are immutable sequences. In an immutable sequence, functions that modify sequence elements such as append(), pop(), and insert() cannot be used.

The operation of tuple deletion: del tuple, but after deletion, the tuple does not exist, and an error will be reported after printing:

2ddbc77f8e01805988fcfecc11bcd307.png

Of course, if the list is deleted using del and then printed, it will also report an error:

7c04bbcdf9b5c840b0c34bcfe1e45038.png

What is the difference between list and tuple

Obviously, lists are mutable and tuples are immutable. Let's compare some of the built-in methods of lists and tuples:

diff =  set(dir(tuple)) - set(dir(list))
print(diff)  # 元组有,但列表没有的成员
# {'__getnewargs__'}


diff = set(dir(list)) - set(dir(tuple))
print(diff) # 列表有,但元组没有成员
# {'append', 'sort', 'clear', 'extend', 'copy', '__setitem__', 'remove', '__imul__', '__iadd__', '__delitem__', 'reverse', '__reversed__', 'insert', 'pop'}

Since tuples cannot be changed, they are generally faster than lists.

Well, this is the end of the study of tuples for the time being. I don’t use tuples for the time being when I usually write scripts. I will share them later when I use them more in some scenarios. You can also take a look at the two articles related to tuples that I wrote before:

Introduction to Tuples in Python

Named tuple namedtuple for advanced usage of python

Follow me, follow Xiaobo, and learn and grow together. Please add V: xiaobotester to join the group for communication/business cooperation with peers.

Guess you like

Origin blog.csdn.net/liboshi123/article/details/130633663