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.
0 Comments