Copying Lists in Python:-
In Python, assigning one variable to another variable simply makes both variables reference the same object in memory. For example, look at the following code:
# Create a list.
list1 = [1, 2, 3, 4]
# Assign the list to the list2 variable.
list2 = list1
After this code executes, both variables list1 and list2 will reference the same list in memory. This is shown in the Figure (given below).
(list1 and list2 reference the same list.)
Suppose you wish to make a copy of the list, so that list1 and list2 reference two separate but identical lists. One way to do this is with a loop that copies each element of the list. Here is an example:
# Create a list with values.
list1 = [1, 2, 3, 4]
# Create an empty list.
list2 = [ ]
# Copy the elements of list1 to list2.
for item in list1:
list2.append(item)
After this code executes, list1 and list2 will reference two separate but identical lists. A simpler and more elegant way to accomplish the same task is to use the concatenation operator, as shown here:
# Create a list with values.
list1 = [1, 2, 3, 4]
# Create a copy of list1.
list2 = [ ] + list1
The last statement in this code concatenates an empty list with list1 and assigns the resulting list to list2. As a result, list 1 and list2 will reference two separate but identical lists.


LinkBack URL
About LinkBacks
Reply With Quote

LinkBacks Enabled by vBSEO
Bookmarks