#Learn Python # lists and tuples [with source code]

1, Lists and tuples

1. Why should lists and tuples always be put together

The basic usage of lists and tuples has been well studied in the basics section. You should keep a basic impression that lists and tuples are an ordered collection that can place any data type, or can be used as a container.

The two most direct differences between them are that the list length is not fixed and variable, and the tuple length is fixed and immutable.

In many places, this difference is called dynamic and static.

The most common error here is to assign or modify the value to the tuple. The error prompt is as follows. You need to know why it occurs?

TypeError: 'tuple' object does not support item assignment

How to add data to tuples? I think you should also be more clear, that is, create a new tuple and splice the new data with the old data.

# Anti crawler notes for dream eraser
my_old_tuple = (1, 2, "a", "b")
my_new_tuple = ("c", "d")

my_tuple = my_old_tuple+my_new_tuple
print(my_tuple)

For the basic part, it should also be noted that if there is only one element in a tuple, it must be written like this (1,), do not omit the comma, omit the data type in the brackets, and finally get the data of that data type.

1.1 slicing of lists and tuples

Lists and tuples are ordered, and they can be sliced in order. Slicing is an operation that takes care of the head and tail, such as the following code.

my_tuple = my_old_tuple+my_new_tuple
print(my_tuple[1:3])

When I first learned slicing, a common error is as follows. The reason for this error is that the words in [] brackets are written as other symbols.

TypeError: tuple indices must be integers or slices, not tuple

1.2 negative index and their mutual conversion

Both list and slice support negative index values, but you need to know that negative index starts from - 1. Why? Think for yourself.

Whisper: it's not because 0 has only one

The two can also be converted to each other. The conversion applies the built-in functions list and tuple. Learn along the functions. There are some built-in functions that can be applied to the list and tuple. We have finished this part when we learn the snowball for the first time. It is very simple.

1.3 storage methods of lists and tuples

Run the following code to view the running results. The list is consistent with the number of tuple elements.

my_list = ["a", "b", "c"]
print(my_list.__sizeof__())

my_tuple = ("a", "b", "c")
print(my_tuple.__sizeof__())

The output results are different. For lists and tuples of the same element data, the system allocates more space to the list

64
48

The first knowledge point is__ sizeof__ (): indicates the size of space allocated by the printing system.

Next, let's conduct a basic test to detect how the system allocates space from the list.

my_list = []
print("Initialization size",my_list.__sizeof__())

my_list.append("a")
print("Size after appending 1 element",my_list.__sizeof__())

my_list.append("b")
print("Size after appending 2 elements",my_list.__sizeof__())

my_list.append("c")
print("Size after appending 3 elements",my_list.__sizeof__())

my_list.append("d")
print("Size after appending 4 elements",my_list.__sizeof__())

my_list.append("e")
print("Size after appending 5 elements",my_list.__sizeof__())

The operation result is:

Initialization size 40
 Size after appending 1 element 72
 Size after appending 2 elements 72
 Size after appending 3 elements 72
 Size after appending 4 elements 72
 Size after appending 5 elements 104

After adding one element, the size becomes 72, and then four elements are added continuously. The size allocated by the system does not change. For five elements, another 32 bytes of space is added. This can be concluded:
The list will increase the space of 4 elements at one time, and will not continue to increase until the space is used up.

Principle of the above code:
In essence, the list is a dynamic array. The list is not the real data stored, but the address (Reference) of each element in memory. Because the list storage is the reference of the element, the memory space occupied by the reference is the same, that is, 8 bytes, and different types of data can be stored.

In a 64 bit operating system, the address occupies 8 bytes. If your computer is 32 bits, the address occupies 4 bytes. Just pay attention.

1.4 application scenarios of lists and tuples

In short, tuples are used for data with fixed element contents, and lists are used for variable data. If you want to keep memory simple, you can directly remember that tuples are used if only 2 or 3 elements are needed, and namedtuple is used if there are many elements. It is a function.

To use namedtuple, you need to import it first.

from collections import namedtuple
help(namedtuple)

The function prototype is as follows:

namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
# Returns a new subclass of tuple with named fields.

Write a test code first:

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x)
print(p.y)

The first two parameters need a simple study.

  • Typename: a parameter of string type. This parameter is easy to understand. Stick to the official explanation. namedtuple() will create a subclass and return the class name according to this typename. For example, Point in the above test code, the created class name is Point, and the second parameter is the future class attribute.
  • field_names: used to name each element of the created tuple. You can pass in a list or tuple, such as ['a ',' B '], (a,b), or a single string separated by commas or spaces such as' a,b' or 'a,b'.

In the above, if you want to see the process of class construction, you can add the parameter verbose, but this parameter is also described on the official website. Some versions do not support it, and there is no such attribute after Python 3.7.

Changed in version 3.6: The verbose and rename parameters became keyword-only arguments.
Changed in version 3.6: Added the module parameter.
Changed in version 3.7: Removed the verbose parameter and the _source attribute.
Changed in version 3.7: Added the defaults parameter and the _field_defaults attribute.

Whether to initialize an empty list with list() or []

This content can use the following code to test the efficiency.

import timeit
a = timeit.timeit('a=list()', number=10000000 )
b = timeit.timeit('a=[]', number=10000000 )
print(a)
print(b)

Operation results:

1.6634819
0.5888171999999998

The conclusion is that [] is faster, because list() is a function call, and the efficiency must be lower.

With the above functions, you can also test which of the same elements is more efficient when initializing lists and tuples.

import timeit
a = timeit.timeit('a=("a","b","c")', number=10000)
b = timeit.timeit('b=["a","b","c"]', number=10000)
print(a)
print(b)

The operation results are as follows:

# Initialize tuple
0.0005571000000000048
# Initialization list
0.002022099999999999

1.5 summary of this blog

This blog focuses on reviewing some basic contents of lists and tuples, and explores the differences between lists and tuples in system allocation. In addition, a namedtuple function is extended for you. Finally, you can expand and understand the timeit module.

Keywords: Python Back-end

Added by Zjoske on Thu, 30 Dec 2021 15:22:24 +0200