Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Go idiom for Python's list.pop() method?

Tags:

list

slice

go

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?

like image 967
Mittenchops Avatar asked Sep 27 '18 23:09

Mittenchops


People also ask

What does list pop () do in Python?

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.

What does the pop () method do to a list?

The pop() method removes the item at the given index from the list and returns the removed item.

Which method is called in a pop () method Python?

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.

Is pop a list method Python?

Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.


1 Answers

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
like image 178
maerics Avatar answered Oct 06 '22 22:10

maerics