Auotolisp Make List
Table of Contents

This function is derived from the Common Lisp make-list function.

A further spinoff of this function is to generate a new list by repeating an existing list. This is called make-list-from and uses a similar argument list, except that the initial-element argument is replaced by an initial-list argument.


Simplistic version

(defun make-list (size initial-element / lst)
  (repeat size (setq lst (cons initial-element lst)))

(defun make-list-from  (size initial-list / lst)
  (cond ((= size (length initial-list)) initial-list)
        ((< size (length initial-list))
         (setq lst (reverse initial-list))
         (repeat (- (length initial-list) size) (setq lst (cdr lst)))
         (reverse lst))
        ((setq lst initial-list)
         (while (< (length lst) (- size (length initial-list))) (setq lst (append initial-list lst)))
         (append lst (make-list-from (- size (length lst)) initial-list)))))

Modified version to optimize speed for longer lists. Help from bruno_vdh [1] for simplifying this without loosing too much speed.

(defun make-list  (size initial-element / lst)
  (if (> size 0)
    (progn (setq lst (list initial-element))
           (while (< (* (length lst) 2) size) (setq lst (append lst lst)))
           (append lst (make-list (- size (length lst)) initial-element)))))

(defun make-list-from  (size initial-list / x)
  (cond ((>= size (length initial-list))
         (setq x initial-list)
         (while (< (* (length x) 2) size) (setq x (append x x)))
         (append x (make-list-from (- size (length x)) initial-list)))
        ((> n 0)
         (setq initial-list (reverse initial-list))
         (repeat (/ (- (length initial-list) size) 4) (setq initial-list (cddddr initial-list)))
         (repeat (rem (- (length initial-list) size) 4) (setq initial-list (cdr initial-list)))
         (reverse initial-list))))

An even more optimized [2] version for long lists

(defun make-list-from  (size initial-list / r)
  (if (= size (length initial-list))
      (setq r (list (mapcar '(lambda (x y) x) initial-list (repeat (rem size (length initial-list)) (setq r (cons 1 r))))))
      (if (< size (length initial-list))
        (car r)
        (apply 'append (repeat (/ size (length initial-list)) (setq r (cons initial-list r))))))))