Home > OS >  Python: better to make new temporary list or make multiple index accesses to same list?
Python: better to make new temporary list or make multiple index accesses to same list?

Time:10-21

I have a 3d list, and I need to compare each element at the lowest level to the max of the list it's in.

if lst[i][j][k] ==  max(lst[i][j]): ...

is this bad practice? it's worse on performance, the only alternative I can think of is

templst = lst[i][j]
if templst[k] == max(templst): ...

but this is worse on memory afaik.

CodePudding user response:

but this is worse on memory afaik

I think you assume that the new variable is a copy of the list, but it isn't. When you do templst = lst[i][j], the only additional memory used is for a reference to the existing list.

CodePudding user response:

Maybe better to replace the if statement with a direct call to the desired index. Should save you calls to the max function.

lst[i][j][np.argmax(lst[i][j])]
  • Related