2

I am learning to use list and slicing and have read that "slices of Python lists create new objects in memory" in the section "Memory Considerations:" by Aaron Hall in Understanding Python's slice notation

Let's say I need to do some read-only operation in some range of a list. Is it recommended to use pointer (c term), because slicing creates new object that I do not need? Assuming that the original list won't be changed, can I say the method2 below is always better?

cost = [1,2,4,5]

#method1
for i in cost[:2]:
    #do something for the first two elements
    print(i)

#method2
for i in range(2):
    #do something for the first two elements
    print(cost[i])
rosepark222
  • 89
  • 3
  • 9
  • `range(2)` creates a new `range` object. It goes out of scope at the same point as the slice. I don't think memory considerations prefer one over the other. – AShelly Dec 19 '18 at 19:12
  • 1
    Introducing unnecessary indices is generally discouraged in Python. Some quick timing shows that method 2 is consistently about twice as slow as method 1, whatever the length of the list (tested from length 10 to 100000000...) – Thierry Lathuille Dec 19 '18 at 19:21
  • 1
    [Premature optimization is the root of all evil](http://c2.com/cgi/wiki?PrematureOptimization) Do whatever makes the code clear, unless you actually encounter performance problems. – Barmar Dec 19 '18 at 21:02

0 Answers0