Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of python list and tuple usage examples

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "python list and tuple use case analysis", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "python list and tuple use case analysis" bar!

Preface

In our actual development, we often need to store a set of data for use. If you have learned other languages, you may know the data structure of Array, it can store multiple data, and access data can be obtained by array subscript. If you are a python developer, you can use more flexible lists (list) and tuples (tuple) for data storage. Let's take a brief look at the basic use of the following tables and tuples.

List

The list is dynamic, the length can be changed, and elements can be added, modified, or deleted at will.

Initialization list a = list () b = [] # you can quickly create listc = list (range (1Magne6)) print ("a:", a) print ("b:", b) print ("c:", c) # a: [] # b: [] # c: [1, 2, 3, 4, 5] add elements through range

Append: add an element to the end of the list

> l = [] > > l.append ("python") > > l ['python']

Extend: expand the list with all the elements in the iterable object

> l = ["python"] > > t = ["java"] > > l.extend (t) > > l ['python',' java']

Insert: inserts an element at a given location. The first parameter is the index of the element to be inserted, so list_name.insert (0, x) inserts the list header

> > l = ["python", "java"] > > l.insert (1, "go") > > l ['python',' go', 'java'] delete elements

Remove (x): removes the first item with the value x from the list. If there is no value to delete, throw an exception

> l = ["python", "java"] > > l.remove ("java") > l ['python'] > > l.remove ("test") Traceback (most recent call last): File ", line 1, in ValueError: list.remove (x): x not in list

Pop: deletes the element at the given location in the list and returns it. If no location is given, pop () deletes and returns the last element in the list

> l = ["python", "java", "go"] > > l.pop () 'go' > > l [' python', 'java'] > > l.pop (1)' java' > > l.pop (1) Traceback (most recent call last): File ", line 1, in IndexError: pop index out of range

Del: keyword in Python that is specifically used to perform delete operations. It can delete not only the entire list, but also some elements of the list.

> l = ["python", "java", "go", "js"] > > del l [0:1] > > l ['java',' go', 'js'] > > del l [0] > > l [' go', 'js']

Clear (): removes all elements from the list. Equivalent to del a [:]

> l = ["python", "java", "go", "js"] > > l.clear () > l []

Ps: note the difference from del here. Clear is cleared, del list_name is deleted, and memory is freed.

Modify element

Modify a single method that can be used by subscript

> l = ["python", "go", "java"] > > l [0] = "PYTHON" > > l ['PYTHON',' go', 'java']

A set of data can be modified by slicing

> l = ["python", "go", "java"] > > l [0:2] = "PYTHON", "GO" > > l ['PYTHON',' GO', 'java'] > l [0:2] = ["python", "go"] > > l [' python', 'go',' java'] query elements

Index (x): method is used to find where an element appears in the list (that is, the index). If the element does not exist, it will result in a ValueError error

> l ['python',' go', 'java'] > > l.index ("python") 0 > > l.index ("python1") Traceback (most recent call last): File ", line 1, in ValueError:' python1' is not in list

Count (): used to count the number of times an element appears in the list

> > l ['python',' go', 'java'] > l.count ("PYTHON") 0 > > l.count ("python") 1 other operations

Sort: sort the elements in the list

> l ['go',' java', 'python'] > > l.sort (reverse=True) > > l [' python', 'java',' go'] > > l.sort () > l ['go',' java', 'python']

Reverse: reversing elements

> l = [1, l.reverse 2, 3, 4, 5] > > 1 () > l [5, 4, 3, 2, 1]

Copy: returns a shallow copy of the list, equivalent to a [:]

> l [5, 4, 3, 2, 1] > a = l.copy () > a [5, 4, 3, 2, 1] python list uses scenario 1-use list to implement stack

Stack (stack) is characterized by last-in, first-out, list implementation is very easy, to add an element to the top of the stack, use append (). To fetch an element from the top of the stack, use pop () without specifying an index.

Stack = [] stack.append (1) stack.append (2) stack.append (3) stack.append (4) stack.pop () # 4stack.pop () # 3stack.pop () # 2stack.pop () # attention catch error 2-implementation queue from collections import dequequeue = deque (["python", "go", "java"]) queue.append ("python") queue.append ("go") print (queue) queue.popleft () queue.popleft () print (queue)

Return the result

Deque (['python',' go', 'java',' python', 'go']) deque ([' java', 'python',' go']) list derivation a = [x * * 2 for x in range (10)] b = [(x, y) for x in [1,2,3] for y in [3,1,4] if x! = y] # nested list derivation matrix = [[1,2,3,4], [5,6] 7, 8], [9, 10, 11, 12],] c = [Row [I] for row in matrix] for i in range (4)] print ("a:", a) print ("b:", b) print ("c:", c)

Return

A: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] b: [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1)] c: [1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] tuples

Tuples are static, fixed in size, and cannot be added, modified or deleted.

Create tuples a = 1, 2, 3print ("a", a) b = (1, 2, 3) print ("b", b) # convert strings to tuples tup1 = tuple ("hello") print ("convert strings into tuples", tup1) # convert lists to tuples list1 = ['Python',' Java', 'tuples,' JavaScript'] tup2 = tuple (list1) print ("convert lists into tuples" Tup2) # convert dictionaries to tuples dict1 = {'a dictionary: 100,'baked: 42, 'dict1: 9} tup3 = tuple (dict1) print ("convert dictionaries to tuples", tup3) # convert intervals to tuples range1 = range (1,6) tup4 = tuple (range1) print ("convert intervals to tuples", tup4)

Return the result

A (1, 2, 3) b (1, 2, 3) converts strings to tuples ('hints,' etrees, 'tuples,' lags, 'JavaScript''), converts lists to tuples ('Python',' Java', 'Category tuples,' JavaScript'), converts dictionaries to tuples ('tuples,' bounds,'c') and converts intervals into tuples (1, 2, 3, 4) 5) access element a = (1,2,3,4,5) # through subscript print (a [0]) # through slice: a [start: end: step] print (a [0: 4:2])

Return the result

1 (1, 3) delete a = (1, 2, 3, 4, 5) del a tuple and list distinguishing tuple is static, list is dynamic

Tuple modification

L = (1jin2jin3jin4) id (l) # 4497372488l = l + (5p6) id (l) # 4494985832

List modification

L = [1Jing 2Jing 3Jing 4] id (l) # 4499169160l = l + [5JE6] id (l) # 4495787016

From the above, we can find that tuples cannot be changed. It is emphasized here that it is not difficult for many beginners to understand this l = l + (5Power6). It is not said that tuples cannot be modified, so why can they be modified here? Remember that although it can be executed here, he has created a new tuple. At this time, the l is not the original l, and you can use the id query (or execute l [0] =-1 and report an error).

I would like to say a few more words here, the static and dynamic here, in vernacular, the list can perform list operations (add, delete, modify). Under general operation behavior, his memory address remains unchanged (checked through id), which is related to his implementation, but the tuple will change, so the new tuple is different from the original one. Usually someone (the interviewer or the developer is not careful) will ask you a = ([1Magne2], 3Power4), why can carry on a [0] .append (3), but id (a) before and after the same, this is the 0 subscript element is the list, the list can be modified.

Lists need more memory, tuples need less memory list_t = [] print ("list initialization size:", list_t.__sizeof__ ()) tuple_t = () print ("tuple initialization size:", tuple_t.__sizeof__ ())

Return the result

List initialization size: 40 tuples initialization size: 24

Have you found that the list is 18 bytes larger than the tuple, so the question is: where did these 18 bytes come from? This is because the list is dynamic and requires storing pointers to point to the corresponding element (8 bytes). In addition, because the elements in the list are variable, you need to store the allocated length size (8 bytes) so that you can track the use of list space in real time. But for tuples, the situation is different, the length of tuples is fixed, and the storage elements are immutable, so the storage space is also fixed.

Lists cannot be hash, tuples can be hashtuple_t = (1,2) print ("tuple hash values:", hash (tuple_t)) list_t = [1,2] print ("list hash values:", hash (list_t))

Execution result

Traceback (most recent call last): File "/ Users/linjian/MonitorCenter/MonitorCenter/apps/t6.py", line 4, in print ("list hash values:", hash (list_t)) TypeError: unhashable type: 'list' tuple hash value: 3713081631934410656

From the above results, we can see that tuples can be hash, but the list is not. If the foundation is solid, it should be reflected that the hash in python needs to satisfy immutable data structures (string str, tuple tuple, object set objects).

Execution efficiency # initialize a list and tuple usage of the same elements (djangoDemo) MonitorCenter% python-m timeit'x = (1MJ 2MJ 3PM 4J 5J 6) '100000000 loops, best of 3: 0.0103 usec per loop (djangoDemo) MonitorCenter% python-m timeit'x = [1Med 2MJ 4MJ 5J 6]' 10000000 loops, best of 3: 0.0514 usec per loop# tuple and list index operation comparison (djangoDemo) MonitorCenter% python-m timeit'x = (1Med 2Met 3Met 4) 5 loops 6) 'Yichexi [3]' 10000000 loops, best of 3: 0.0267 usec per loop (djangoDemo) MonitorCenter% python-m timeit'x = (1 Meng 2 Meng 3 Ji 4 5 Jing 6)''yellowx [3]' 10000000 loops, best of 3: 0.0265 usec per loop

The above running result shows that the tuple initialization is much faster than the list, about five times the gap, but there is not much difference in the speed of index operation.

So far, we can briefly summarize the differences between lists and tuples as follows:

Tuples are initialized with tuple () or (), and lists are initialized with list () or []

Tuples are static, while lists are dynamic

Lists need more memory, tuples need less memory

Lists cannot be hash, tuples can be hash

The efficiency of tuple initialization is higher than that of list, but there is not much difference in index operation.

Tuple and list usage scenarios

Let's talk about it before using the scenario. In the python background, we do some resource caching for static data. Usually, because of the garbage collection mechanism, some variables are not used, python will reclaim the memory they occupy, but for some static variables (such as tuples), when they are not occupied (tuples of length 1 to 20), python will temporarily cache this part of memory, so that you can no longer make a request to the operating system next time. Allocate memory resources, but directly use the previous memory space in the cache, which greatly speeds up the running speed of the program. So sometimes the amount of data is small, and I often use tuples instead of lists. So far, we can simply summarize that the scenario can be as follows:

If the data is immutable, we can consider using tuples, such as gender type, city information returned, etc.

If the data is variable, we will consider using a list, such as the web page visited by the user that day, etc.

Is it more efficient to use list () or [] to expand knowledge and create empty lists? (djangoDemo) MonitorCenter% python-m timeit 'x=list () '10000000 loops, best of 3: 0.087 usec per loop (djangoDemo) MonitorCenter% python-m timeit'x = []' 100000000 loops, best of 3: 0.0177 usec per loop

Through the above test, we can know that it is [] fast. List () function call. The function call in python creates a stack and checks parameters. [] is a built-in C function that can be called directly, so it is more efficient.

When performing the multiplication operation, is it * = more efficient or *? (djangoDemo) MonitorCenter% python-m timeit'x = [1Met 2 timeit'x]'x = x * 3 million 10 million loops, best of 3: 0.104 usec per loop, best of 3: 0.0903 usec per loop (djangoDemo) MonitorCenter% python-m timeit'x =

It can be seen from the results that * the efficiency will be lower. * will be pre-allocated in the middle, and the capacity will be expanded when it is insufficient, but * the size will be allocated according to the amount of each time

Why is the output like this? List_1 = [1,2,3,4] list_2 = [1,2,3,4] list_3 = [1,2,3,4] list_4 = [1,2,3,4] for idx, item in enumerate (list_1): del itemfor idx, item in enumerate (list_2): list_2.remove (item) for idx, item in enumerate (list_3 [:]): list_3.remove (item) for idx Item in enumerate (list_4): list_4.pop (idx) print ("list_1", list_1) print ("list_2", list_2) print ("list_3", list_3) print ("list_4", list_4)

Result

List_1 [1, 2, 3, 4] list_2 [2, 4] list_3 [] list_4 [2, 4]

Why is the output of list_2 [2pr 4]? Because after the first deletion, the list_2 becomes [2jing3jin4], and then after the deletion turns to the second data, that is, 3 (most of them think it is 2, but 2 changes from the original table 2 to 1), you can see the following

Give next element: 00-> 11 22 33 4give next element: 10 21-> 32 4give next element: 20 21 4

Why is list_3 []? remember that when we said copy, copy was equal to [:] (shallow copy), so the data polled and deleted were not the same memory.

List_4 can think in conjunction with list_2, because the first deletion and the second deletion is subscript 2, but the data has changed. The data of subscript 2 is not the original 2, but 3.

Thank you for your reading, the above is the "python list and tuple use case analysis" content, after the study of this article, I believe you have a deeper understanding of the python list and tuple use case analysis of this problem, the specific use also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report