Search code examples
pythonemacselisp

Is there a concise emacs lisp equivalent of Python's [n:m] list slices?


One thing I find myself missing in emacs lisp is, surprisingly, a particular bit of list manipulation. I miss Python's concise list slicing.

>>> mylist = ["foo", "bar", "baz", "qux", "frobnitz"]
>>> mylist[1:4]
['bar', 'baz', 'qux']

I see the functions butlast and nthcdr in the emacs documentation, which would give the same results from code like this:

(setq mylist '("foo" "bar" "baz" "qux" "frobnitz"))
(butlast (nthcdr 1 mylist) 1)
;; ("bar" "baz" "qux")

Is there a more concise way of getting a list slice than combining butlast and nthcdr?


Solution

  • Sure there is:

    (require 'cl-lib)
    (setq mylist '("foo" "bar" "baz" "qux" "frobnitz"))
    (cl-subseq mylist 1 4)
    ;; ("bar" "baz" "qux")
    

    In modern Emacs, please note cl is deprecated see In Emacs, what does this error mean? "Warning: cl package required at runtime"