Python Code for Memory Efficiency