-2

My code is as follows:

nums = [1,2,3,4,5,6,7,8,9,10]
k = 3
k = k % len(nums)
nums[:] = nums[-k:] + nums[:-k]       

Does [ : ] create a copy of the list?

In that case, is extra memory allocated if I use this code? Is it O(1)?

philipxy
  • 14,867
  • 6
  • 39
  • 83
jaroslaw
  • 23
  • 2
  • 1
    Regardless of whether extra memory is allocated (yes, it is, but for the temporary result of `+`, not for `nums[:]`), it should be clear that the code cannot be O(1) because it needs to move each one of the elements of `num`. So it's O(N) (where N is the size of `num`), and the only question is what the constant multiplier might be. – rici Oct 20 '22 at 17:06

1 Answers1

-3

[:] does create a copy.

# data
x = [1, 2, 3]
y = x[:]

# changing x value
x[0] = 2

# checking out the results
print(x, y)

[2,2,3] [1,2,3]

Check out Python Slice Assignment Memory Usage

philipxy
  • 14,867
  • 6
  • 39
  • 83