0

If I create a function in python that takes in an array and pops a value, will the array be permanently changed outside of the function?

ie

func popRandom(array):
    array.shuffle()
    return array.pop()

Will the array be permanently altered outside of the function? Because that's what I'm going for.

GT.
  • 764
  • 1
  • 8
  • 30
  • 3
    Yes mutating an array in the function changes the original (including the `shuffle`). But why not test it yourself? – Mark Dec 14 '20 at 15:33
  • 2
    Also, python declares functions with `def`, not `func`. – Aplet123 Dec 14 '20 at 15:35
  • Ahh that's true. I'm writing it within a big code base and it didn't occur to me to test a small sample in on online IDE or something!! – GT. Dec 14 '20 at 15:35
  • Aplet123 that's true, I'm actually using GDScript which uses func instead of def but is otherwise similar to python – GT. Dec 14 '20 at 15:35
  • 1
    BTW, there's no need to shuffle the array for this. `pop()` takes an optional argument with the index to remove, so you can use `return array.pop(random.randrange(len(array))` – Barmar Dec 14 '20 at 15:39
  • Barmar is there a speed advantage to that? Personally I feel like it's less readable, but if it's significantly faster than maybe it's worth it? – GT. Dec 14 '20 at 15:46
  • @Barmar [random.choice(array)](https://docs.python.org/3/library/random.html#random.choice) is an even better choice (sic). EDIT: oh yeah my bad that won't remove the item from the list. – Mike Roll Dec 14 '20 at 15:47
  • 2
    @G.T. shuffling an array has to be much slower than removing one randomly selected element. – Barmar Dec 14 '20 at 15:51

0 Answers0