Categories: PythonPython List

How to copy a list in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

The mechanism for copying a list in Python appears somewhat different than in other programming languages. If you just use equal symbol to assign an existing list to a new one, both objects refer to the same one which is stored in the computers memory. Say we have a list for favorite languages and create a new one using equal symbol.

fav_prog = ['python','C','C++','Java']
fav_prog_2 = fav_prog
#display the new list
fav_prog_2
#output
['python', 'C', 'C++', 'Java']
#now we add one element into one of the two lists
fav_prog.append('Ruby')
#show first list
fav_prog 
#output
['python', 'C', 'C++', 'Java', 'Ruby']
#show the second list
fav_prog_2
#output
Out[4]: ['python', 'C', 'C++', 'Java', 'Ruby']

It is clear that both lists have new element added, even we have just append element to only one of them. So if you want to avoid such unexpected result, we have to use slice symbol , “:” in Python to copy list.

#create the first list
fav_prog = ['python','C','C++','Java']
#copy a list using colon symbol
fav_prog_2 = fav_prog[:]
#show second list
fav_prog_2
#output
['python', 'C', 'C++', 'Java']
#now we add one element to the first list
fav_prog.append('Ruby')
#show again the first list
fav_prog 
#output
['python', 'C', 'C++', 'Java', 'Ruby']
#show again the second list
fav_prog_2
#output
['python', 'C', 'C++', 'Java']
#we add one element to the second list
fav_prog_2.append("PHP")
#show again the second list
fav_prog_2
#output
['python', 'C', 'C++', 'Java', 'PHP']
#show the first list again
fav_prog
#output
['python', 'C', 'C++', 'Java', 'Ruby']

It is ok that two lists now refer to two individual objects, which is what we want to see.

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Fine tuning a Hugging Face transformer model for multi-track music generation

To train a PyTorch Transformer for multi-track music generation, the standard paradigm is to convert…

3 weeks ago

what are Transformer, LLM , and GPT

In the field of AI and Natural Language Processing (NLP), The Transformer is the engine…

3 weeks ago

Main framework for PyTorch music generation model

If your goal is purely symbolic melody generation (e.g., generating MIDI files or notes rather…

4 weeks ago

affine_grid() in pytorch

According to PyTorch document, In PyTorch, torch.nn.functional.affine_grid generates a 2D or 3D flow field (sampling…

3 months ago

How to create an Android mobile app with a deep learning AI model ?

Creating an Android mobile app with a deep learning AI model involves several key steps:…

12 months ago

Download source files for R Machine learning

Click here to go to source files for R Machine Learning

1 year ago