0

I have a query. I understand that python passed by object (which I think is similar to passing by reference in C++). I have a function which I loop

def GrowListandShrinkDataFrame(DF, m_list, criteria):

    FoundDF = DF[DF['Criteria'] == criteria ]
    if not FoundDF.empty:
         FoundDF['X1'] = FoundDF['X1'] - FoundDF['X2']
         m_list.append(dict{'Criteria' : criteria,
                            'X1' : FoundDF['X1'],
                            'X2' : FoundDF['X2']})
         droplist =DF.index[(DF['X1'] < 0)].tolist()
         DF = DF.drop(droplist)

def main():
    for rows in df.itertuples():
         GrowListandShrinkDataFrame(df2, listA, rows[1])
         print(len(listA))
         print(df2.shape[0])

but this is the observation i get for each iteration

  • The list grows in size
  • Dataframe did not reduce in size

IS my understanding of pass by object wrong? Or some issue with my coding?

Thanks

user1538798
  • 1,075
  • 3
  • 17
  • 42
  • 2
    Reassigning the variable `DF` inside `GrowListandShrinkDataFrame` does not affect the `DF` variable in `main`. Python semantics are *not* like passing by reference in C++. – khelwood Mar 02 '20 at 08:56
  • @khelwood. THanks! but why does the list grow in size? is it because of separate treatment by python – user1538798 Mar 02 '20 at 08:57
  • 2
    list grows beacuse you don't use `=` to assign new object to local variable `m_list`. But with `DataFrame` you use `=` and it assign new object to this variable so it has no access to old one. Maybe if you use `df.drop(inplace=True)` without `DF = ` then it will change original DataFrame and it will change size. – furas Mar 02 '20 at 08:59
  • It's because you are treating it differently. The parameters received by the function are the same object as those passed in, but in different variables. So mutating the objects affects them outside the function; but reassigning the variables does not. – khelwood Mar 02 '20 at 08:59
  • @furas. Thanks learn something today – user1538798 Mar 02 '20 at 09:00

0 Answers0