optimized memory by working on input list