Search code examples
python-3.xpandasdataframememoryunique

Unique function in python


for i in df["col"].unique():
   ...

Here unique function is called after each iteration of loop or is it just called once and stores the result in memory??

Asking this just to check if unique function is executed after every iteration then there is chance that even in next iteration i might be same as in previous iteration.

Ex first time unique function is called then df["col"].unique() gives [1,2] so i would be 1 for first iteration and in second iteration unique function is again called and i may again get 1 as value.


Solution

  • The construction you are using first calculates the .unique() function and uses the result of that function, if iterable, to loop over.

    If you'd want the loop to evaluate a function every iteration, you could use structures like:

    list = [x.function() for x in items]
    

    check this link for more information: https://opensource.com/article/18/3/loop-better-deeper-look-iteration-python