Pandas Series is size immutable

I know, Series (in pandas) is size-immutable. That means, once a Series object is created, it cannot be changed. If we try to change it, it creates a new Series.

Consider the following code:

import pandas as pd
s = pd.Series([10, 20, 30, 40], index = ["A", "B", "C", "D"])
print(s)
print(id(s))    #Statement 1
s["R"] = 90    #Statement 2
print(s)
print(id(s))    #Statement 3

In the above code, why Statement 1 and Statement 3 are giving the same output, if a new Series object is created due to Statement 2?

This is simply not the case and I’m not sure how you got that impression. If a Series is part of a DataFrame, then attempting to add another value like this will silently fail, in order to keep the DataFrame rectangular. But a separately created Series is just as mutable and extensible as a list or dictionary. (Well, I guess the interface is a little different.)

Aside from that, code like s["R"] = 90 can’t meaningfully create a new Series. Python translates this into a call to the __setitem__ method of s and ignores the return value (it should return None but as far as I can tell this is not enforced). If Pandas did create a new Series it would just be immediately garbage-collected. There’s nothing in this code that can rebind the s name.

2 Likes