Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python memory use in loop function call vs variable assigment

Lets say I have a dataframe which I want to transform into list of dictionaries and loop over them.

What would be more efficient?

df = some_dataframe
df_as_list = df.to_dict('records')

for i in df_as_list:
    requests.get(i['url'])

or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = some_dataframe
for i in df.to_dict('records'):
    requests.get(i['url'])

Does the second example call to_dict() on every loop?

>Solution :

There is only one call to to_dict. The for loop is basically equivalent to

t = iter(df.to_dict('records'))
while True:
    try:
        i = next(t)
    except StopIteration:
        break

    requests.get(i['url'])

It doesn’t matter whether you assign the result of df.to_dict to a variable or not, because the result is simply passed to iter, and that iterable is passed to next multiple times.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading