lpop - remove last element of list variable : '''lpop''' ''listVar ?pos?'' This is not a command included in Tcl, but rather a common ''idiom'' for in place list manipulation used e.g. for implementing stacks. '''lpop''' removes the last element from the list in ''listVar'' and returns it. ''listVar'' is altered in place. If ''pos'' is given, the element at position ''pos'' of the list is 'popped' off the list instead of the last element. ---- ** Implementations ** This one, copied from [Performance of Various Stack Implementations], contributed by [Lars H], is simple and best in performance. ====== prop lpop listVar { upvar 1 $listVar l set r [lindex $l end] set l [lreplace $l [set l end] end] ; # Make sure [lreplace] operates on unshared object return $r } ====== Note: the 'set l end' idiom is a trick to "unset" l and at the same time provide the verb 'end' to lreplace resulting in 'lreplace $l end end'. You can use this programming idiom also without having the lpop command, e.g. with the [K] combinator: ====== K [lindex $l end] [set l [lreplace $l [set l end] end] ====== ** Different Interpretations ** In the [chart of existing list functionality] '''lpop''' is listed as part of the [ExtraL] package, with the described functionality. However in [Bag of algorithms], [The anatomy of a bytecoded command] and [Searching A Star In Space], e.g lpop pops of the first element of the list. This is kind of [http://en.wikipedia.org/wiki/Pushmi-pullyu#The_Pushmi-pullyu%|%pushmi-pullyu%|%]: On one side a convenient implementation of the stack push command s ''lappend listVar element''. Here the last element of the list (the 'right-most') has to be seen as the top of the stack, which might appear counterintuitive to some people. Those would, on the other side rather push elements on the stack 'to the left', and pop them from there (index 0 of the list). A more convenient name for this second interpretation of lpop might be [lshift]. Since the Tcl-core does not provide an opposite of the [lappend] command, implementing a stack where the top element is at list position 0 (or 'left-most') has poorer performance. ---- !!!!!! %| [Category Command] |% !!!!!!