About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Monday, September 2, 2019

List is mutable in Python

Lets check this out by writing a small script, which will create two list and copy both the list to form another list.

a = ['neha','sharma']
b=[
10,12]
print('a location:', id(a), ' b location:', id(b))
c=[a
,b]
print('c list [a,b]:', c, ' c location :', id(c))

Output:
a location: 14501328  b location: 14502488
c list [a,b]: [['neha', 'sharma'], [10, 12]]  c location : 51493064

Now lets insert a value at the end of second list that is b and check if it is affecting list c

b.insert(2,13)
print('b after inserting 13', b)
print('b locatiton after inserting new value :', id(b))
print(id(c))

Output
b after inserting 13 [10, 12, 13]
b locatiton after inserting new value : 14502488
c after changing b :   [['neha', 'sharma'], [10, 12, 13]]  c location after change : 51493064


Here we can see, changing the list of b, changed the list of c, without changing the memory location. So here we can see list is mutable.

Complete Code:

a = ['neha','sharma']
b=[
10,12]
print('a location:', id(a), ' b location:', id(b))
c=[a
,b]
print('c list [a,b]:', c, ' c location :', id(c))
b.insert(
2,13)
print('b after inserting 13', b)
print('b locatiton after inserting new value :', id(b))
print('c after changing b :  ',c, ' c location after change :', id(c))


But what if we don’t want c to get changed with the change in b…. let’s check this in next post..


Data Science with…Python J
Post Reference: Vikram Aristocratic Elfin Share

No comments:

Post a Comment