Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

An example Analysis of shallow replication in Clippers, Java and Python

Shulou Source: shulou.com Published: 2022-06-01 19:10:26 10月05日 Update

This article introduces the relevant knowledge of "shallow copy example Analysis in Clearing, Java, Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

01

The question of shallow copy and deep copy of the object is often asked in the interview, whether it is Clippers, Java, or Python. Today, we take Python as an example to illustrate the problem of shallow replication.

02

Start with copy () of List

Let's start with something simple, as follows:

Monkeys = ['jone','yone','mary']

Wukongs = monkeys.copy ()

Print (wukongs)

> ['jone',' yone', 'mary']

We successfully cloned wukongs.

At this point, it's just a copy, and you can't see what a shallow copy is.

03

Next, let's look at shallow replication.

We add a group of animals to the monkeys population, as follows, and then copy the monkeys.

Monkeys.append (['nuzha','honghaier'])

Print (monkeys)

# > ['jone',' yone', 'mary', [' nuzha', 'honghaier']]

Print (wukongs)

# > ['jone',' yone', 'mary']

# copy mokeys to wukongs again

Wukongs = monkeys.copy ()

Print (wukongs)

# >

Print wukongs at this time, and you can see:

['jone',' yone', 'mary', [' nuzha', 'honghaier']]

This is not surprising at all, and then there is the moment to witness miracles:

Wukongs [- 1] .append ('houzi')

Print (wukongs)

Print (monkeys)

When we add an animal: houzi from the last element of wukongs, which is also a list, we only add an animal to wukongs. It's not surprising to print it at this time, but print monkeys and find that it also has houzi.

['jone',' yone', 'mary', [' nuzha', 'honghaier',' houzi']] ['jone',' yone', 'mary', [' nuzha', 'honghaier',' houzi']]

This is shallow copy, when an element in a list is an object, such as list, tuple, dict and self-built classes, if you execute copy (), the element only copies the pointer value and does not copy its memory recursively. Therefore, it will cause the above phenomenon, because it is two references to the same memory address.

This is the end of the content of "shallow copy example Analysis in Clippers, Java, Python". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Next elements animals problems analysis memory content again just objects that is more knowledge surprise practicality success learning achievement dilemma address miracle Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux NVidia Xiaomi Shulou Information Docker