Given;
(setq whole '(group1 group2(element1 element2(suba subb subc)
element3) group3))
I would to print some list of that list, like element2 sublist.
How can i do it?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.
Sign up to join this communityWelcome to the Emacs StackExchange site!
List Structure Clarification
I suspect you made an error in notating your lisp object. It looks like you were maybe trying to add an identifier to the second group? Check out alists and plists for helpful list structures with keys. They may be correspond to the object you had in mind.
Maybe this will help clarify things. Your list object:
'(group1 group2(element1 element2(suba subb subc) element3) group3)
Should, at a minim, have spaces to make it clear that it is indeed lisp code (and not a mutant child of Scheme and JavaScript):
'(group1 group2 (element1 element2 (suba subb subc) element3) group3)
In an expanded form for readability (with newlines and indentation) expresses exactly the same structure which may not be what you intended:
(Preserving the symbol names in the original post; 'group1' 'group2' are misnomers)
'(
group1 ; first element of the list (accessed by (elt whole 0) since lists are indexed from zero)
group2 ; second element (another way of accessing is (nth 1 whole) which is functionally the same as (elt whole 1)
( ; third element - is the list you were talking about accessing
element1 ; first element of your nested list
element2 ; second element of your nested list
( ; third element of the third element
suba ; first element of the third element of the third element
subb
subc
)
element3
)
group3 ; fourth element of the top-level list
)
Accessing lists
In addition to elt
and nth
you should also look at using car
and cdr
. Once you understand these and their many variations you should have a strong grasp of how lists work in lisp.
(car whole) ; evaluates to the 'group1 symbol you have
(cdr whole) ; evaluates to the rest of the list after 'group1
(cadr whole) ; evaluates to the 'group2 symbol you have
(cddr whole) ; evaluates to the 'group2 symbol you have
Printing
For printing elements of uncertain type you might want to consider using prin1
.
(cdr (assq 'suba whole))
to get the value if you have used the key 'suba
to store the value (ex: (setq whole '((suba . "My value")))
). Note that lists don't inherently represent an en.wikipedia.org/wiki/Associative_array data structure. alists only have 'keys' or 'names' because they follow a common convention of storing the key as the car of each cons element.
C-h f elt
to access list elements.