TransWikia.com

Select element in a multidimension list containing one element

Mathematica Asked on December 11, 2020

Imagine that I have a list like:

list={{{{1}}}}

To access the number 1, I could do list[[1]][[1]][[1]][[1]]

Of course it is very ugly but this is how I would do it given my knowledge.

What is the cleanest way to access the number in such list ? Can I go "from the bottom to the up" ?

3 Answers

First: You can put a list of indices into a single pair of [[...]] to access elements of nested lists (which already improves readability a lot):

list = {{{{1, 2}}}}
(* {{{{1, 2}}}} *)

list[[1]][[1]][[1]][[1]]
(* 1 *)

list[[1, 1, 1, 1]]
(* 1 *)

Going from the bottom up is generally more difficult: For the case of a (nested) list of integers (or other atomic expressions, see AtomQ), you can take a look at Level to get the deepest parts:

Level[list, {-1}]
(* {1, 2} *)

Level[list, {-1}][[1]]
(* 1 *)

Answered by Lukas Lang on December 11, 2020

Try also this:

f[x_, a_] := x[[a]];   

 Fold[f, list, Table[1, Depth[list] - 1]]

(* 1 *)

Have fun!

Answered by Alexei Boulbitch on December 11, 2020

If you want the position specification required to Extract a particular element, use Position.

pos = Position[list, 1]
(* {{1, 1, 1, 1}} *)

Extract[list, pos]
(* {1} *}

Answered by Rohit Namjoshi on December 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP