In Python, I have the following:
i = series.index(s) # standard Python list.index() function
tmp = series.pop(i)
blah = f(tmp)
series.append(tmp)
In converting this to Go, I am looking for a similar way of retrieving an item from a slice by index, doing something with it, then putting the original item at the end of my slice.
From here, I have arrived at the following:
i = Index(series, s) // my custom index function...
tmp, series = series[i], series[i+1:]
blah := f(tmp)
series = append(series, tmp)
But this fails at the end of lists:
panic: runtime error: slice bounds out of range
How would I idiomatically translate this slice.pop()
into Go?
List pop in Python is a pre-defined, in-built function that removes an item at the specified index from the list. You can also use pop in Python without mentioning the index value. In such cases, the pop() function will remove the last element of the list.
The pop() method removes the item at the given index from the list and returns the removed item.
pop() is a method of the complex datatype called list. The list is among the most commonly used complex datatype in python, and the pop() method is responsible for popping an item from the python list. The pop method will remove an item from a given index of the list and returns the removed item.
Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.
Another option would be to create a function that takes a pointer to an int slice which modifies the argument to remove the last value and return it:
func pop(xs *[]int) int {
x := (*xs)[len(*xs)-1] // Store the last value to return.
*xs = (*xs)[:len(*xs)-1] // Remove the last value from the slice.
return x
}
For example (Go Playground):
xs := []int{1, 2, 3} // => xs=[1, 2, 3]
x := pop(&xs) // => xs=[1, 2], x=3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With