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

The assignment method of list list in Python and how to deal with the problems encountered

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "the assignment method of list list in Python and how to deal with the problems encountered". In daily operation, I believe that many people have doubts about the assignment method of list list in Python and how to deal with the problems encountered. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer "the assignment method of list list in Python and how to deal with the problems encountered". Next, please follow the editor to study!

The origin of the problem:

The reason for this article is that when we use list's direct assignment bdistribua, the result is different than expected. Later, we found that directly using the equal sign = to assign the list will cause a series of problems, so record the difference among assignment, shallow copy and deep copy.

1. List list assignment method

In python, object assignment is a simple object reference, which is different from C++

The following example is shown:

A = ['await,' baked,'c'] b = a # using a simple = assign print (astatb) # here is the output: True

In the above case, b and an are the same, they point to the same piece of memory, b is just an alias for a, is a reference. We can use whether an and b are the same or not, and return True, indicating that they have the same address and the same content.

Assignment operations (including objects as parameters, return values) do not open up new memory space, it simply copies references to new objects. That is, there is no memory overhead other than the name b.

If you modify a, you affect b; by the same token, modifying b affects A. The following example attempts to modify b with the addition of a new element 'dstores. By observing the output, it is found that when you modify list b, list an is also modified because both use the same memory space.

A = ['await,' baked,'c'] b = ab.append ('d') print ('a = {} '.format (a)) print (' b = {} '.format (b)) # the following is the output: a = [' axed, 'baked,' cased,'d'] b = ['axed,' baked, 'clocked,' d'] 2. Shallow copy (shallow copy)

A shallow copy creates a new object whose content is a reference to the original object.

There are three forms of shallow copy: slicing operation, factory function, and copy function in the copy module.

For example, for the above a:

1. Slicing operation: B = a [:] or b = [each for each in a]

2. Factory function: B = list (a)

3. Copy function: B = copy.copy (a) # use import copy module

The b produced by shallow copy is no longer a. Using is, you can find that they are not the same object. Using id to check, you can find that they do not point to the same piece of memory. But when we use id (x) for x in an and id (x) for x in b, we can see that the addresses of the elements they contain are the same.

In this case, an and b are different objects, and modifying b will not theoretically affect a. For example, b.append ([4d5]).

The code effect is as follows:

A = ['yellow',' red']] b = a [:] # use slicing operation to assign values to list b b.append ('green') # add elements to list b print (' a = {} '.format (a)) print (' b = {} '.format (b)) # here is the output: a = [' await, 'baked,' c'' The element in ['yellow',' red']] # a does not change b = ['yellow',' red'], 'green'] # b adds an element' green'

But note: the reason why a shallow copy is called a shallow copy is that it only copies one layer, and there is a nested list in a, and if we modify it, the situation will be different.

     a [3] .append ("blue"). Look at b and you will see that b has also changed. This is because you modified the nested list. Modifying the outer element modifies its references so that they point to another location, modifies the elements in the nested list, and the address of the list is changed, pointing to the same location.

The code is as follows:

A = [yellow', 'red']] b = a [:] # uses a slicing operation to assign a [3] .append (' blue') # to the third element in a list 'blue',' because a [3] itself is a list, so the element 'blue', is added to the list as shown in the output. Print ('a = {} '.format (a)) print (' b = {} '.format (b)) # the following is the output: a = [' await, 'baked,' cached, ['yellow',' red', 'blue']] b = [' yellow', 'red',' blue'] 3. Deep copy

There is only one form of deep copy, the deepcopy function in the copy module.

Corresponding to the shallow copy, the deep copy copies all the elements of the object, including multiple layers of nested elements. Therefore, its time and space cost is high.

Also for la, if you use b = copy.deepcopy (a), modifying b will not affect a. Even if the nested list has a deeper level, it will not have any impact, because the deeply copied object is a completely new object and no longer has anything to do with the original object.

The example code is as follows:

Import copya = ['yellow',' red']] b = copy.deepcopy (a) # make a deep copy of a by deep copy b.append ('xyz') print (' a = {} '.format (a)) print (' b = {} '.format (b)) # the output is as follows: a = [' a', 'baked,' cased, ['yellow'] 'red']] # use deep copy Modifications to b will not affect ab = ['yellow',' red'], 'xyz']

Or use the following code:

Import copya = ['yellow',' red']] b = copy.deepcopy (a) # make a deep copy of a by deep copy a [3] .append ('crazy') print (' a = {} '.format (a) print (' b = {} '.format (b)) # the following is the output: a = [' await, 'baked,' cached, ['yellow'] 'red',' crazy']] b = ['a', 'baked,' cased, ['yellow',' red']] # modifications to a will not affect b

Or use the following code:

Import copya = ['yellow',' red']] b = copy.deepcopy (a) # make a deep copy of a by deep copy a [3] .append ('crazy') b.append (' dddd') print ('a = {} '.format (a) print (' b = {} '.format (b)) # here is the output: a = [' ajar, 'baked,' c'' ['yellow',' red', 'crazy']] b = [' yellow', 'red'],' dddd'] 4. Reminder about copy operation

1. For non-container types, such as numbers, characters, and other "atomic" types, there is no copy. All that is generated are references to the original object.

2. If the tuple variable value contains an atomic type object, even if a deep copy is used, you can only get a shallow copy.

At this point, the study on "the assignment method of list list in Python and how to deal with the problems encountered" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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