# Python's “pop” equivalent in Mathematica

I will like to know if there is an equivalent to python's pop method, here is how it's done in Python:

>>> my_list = [1,2,3,4,5]
>>> my_list
[1, 2, 3, 4, 5]
>>> value = my_list.pop(0)
>>> value
1
>>> my_list
[2, 3, 4, 5]


With pop you get and delete an element from a list.

• Try the commands First (to get the first element) and Rest (to get the remainder of the elements) – bill s Jan 15 '17 at 18:21
• @bills and if I want to do pop(4)? The idea is right but i want to be able to grab any element on the list. – Iván Martín Jan 15 '17 at 18:24
• Then use Part: list[[1;;4]] and list[[5;;All]] – bill s Jan 15 '17 at 18:26
• Why are you looking for an equivalent? In Mathematica it is generally not a good idea to mutate data structures. There is no equivalent because such a function (that both modifies its argument and returns something) really has no place in a language like Mathematica. Are you looking for an efficient stack data structure? If so, consider a nested list like {3, {2, {1, {}}}}. Use First and Rest to pop an item from it. – Szabolcs Jan 15 '17 at 18:42
• pop is like Part[ ] but with an additional side effect. In Mathematica we normally try to avoid side effects. However we have functions like AppendTo that work like that. – Gustavo Delfino Jan 15 '17 at 18:44

There is no direct equivalent. You could use something like this:

SetAttributes[pop, HoldFirst]
pop[list_, n_] := With[{item = list[[n]]}, list = Delete[list, n]; item]

mylist = {1, 2, 3, 4, 5};

pop[mylist, 4]
(* 4 *)

mylist
(* {1, 2, 3, 5} *)

• See @JoseLuisMartin 's answer. Surprisingly there is an equivalent. – QuantumDot Jan 17 '17 at 15:05
• @QuantumDot I wouldn't say that's equivalent - pop alters the list whereas TakeDrop returns a new list. – Simon Woods Jan 17 '17 at 18:44
• Ah yes, indeed. – QuantumDot Jan 17 '17 at 21:00

TakeDrop[list,seq]

list = {1, 2, 2, 4, 5, 6};
seq  = {2, 3};
pair = TakeDrop[list, seq] (* {{2, 2}, {1, 4, 5, 6}} *)
list = pair[]           (* {1, 4, 5, 6} *)
pop = pair[]            (* {2,2} *)


Here is a simple way that I think mimics the Python script well.

myList = Range;
{value, myList} = {#, {##2}} & @@ myList;
Column[{value, myList}] Introduced in v10, you can use Nothing:

mylist = {1, 2, 3, 4, 5};

(* save the particular item, if you need it *)
item = mylist[];

mylist[] = Nothing;
(* mylist = {2, 3, 4, 5} *)

mylist == {2, 3, 4, 5}
(* True *)

mylist === {2, 3, 4, 5}
(* True *)