0

below is my code

s2 = 'radio'   
l1 = [i for i in s2]   
print(l1)   
l2 = l1  
l2.reverse()  
print(l1)  
print(l2)  

output:
*******************************************
['r', 'a', 'd', 'i', 'o']  
['o', 'i', 'd', 'a', 'r']                           
['o', 'i', 'd', 'a', 'r']

why the value of l1 is also getting reversed when i am reversing only l2.

Please help.

1 Answers1

0

in python, assignments are done by reference, which means that the line

l2 = l1

is literally assigning the variable l2 to the same object in memory as l1. If your goal is to make a copy of the list, you could use the copy module

import copy
# shallow copy
l2 = copy.copy(l1)
# deep copy
l2 = copy.deepcopy(l1)

a shallow copy will make a new copy of the list, without copying over any elements within that list. While a deep copy will copy everything within the list recursively.

you could also take advantage of the copying behavior of list slices to make a shallow copy implicitly

# take a slice of l1 that encompasses all of l1
l2 = l1[:]

if using python 3.3+ you can also just use the copy method of the list instance itself

l2 = l1.copy()
Bitsplease
  • 306
  • 2
  • 12