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

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago