Wolfram: Position in a List

By Xah Lee. Date: . Last updated: .

Index of a Element

Index is an integer, that indicates the nth element.

For example, if we have

{a, {{b,c}, d}, e}

Position of a Subexpression

A position is a list of integers that uniquely specify a part of expression.

For example, if we have

{a, {{b,c}, d}, e}

Index counting start at 1. Index 0 means the Head of Expression.

Get Position of a Element

Position[expr, pattern]

Return a list of positions that Pattern occur in expression. If no exist, return a empty list.

  • Position[expr, pattern, levelSpec] → limit to Level Spec.
  • Position[expr, pattern, levelSpec, n] → return first n.

Position

(* position of e is {3} *)
Position[ {a,{{b,c},a},e}, e ]
(* {{3}} *)

(* position of a is {1} and {2, 2} *)
Position[ {a,{{b,c},a},e}, a ]
(* {{1}, {2, 2}} *)

(* when not found, empty list *)
Position[ {a,{{b,c},a},e}, m ]
(* {} *)

(* position of b *)
Position[ {a,{{b,c},a},e}, b ]
(* {{2, 1, 1}} *)

(* position of {b, c} *)
Position[ {a,{{b,c},a},e}, {b, c} ]
(* {{2, 1}} *)

Limit Depth Level

(* find 7, only in level 1 *)
Position[ {7, {{2, 7}, 2}, 7}, 7, {1} ]
(* {{1}, {3}} *)

(* find 7, only in level 2 *)
Position[ {7, {{2, 7}, 2}, 7}, 7, {2} ]
(* {} *)

(* find 7, only in level 3 *)
Position[ {7, {{2, 7}, 2}, 7}, 7, {3} ]
(* {{2, 1, 2}} *)

(* find 7, in all levels *)
Position[ {7, {{2, 7}, 2}, 7}, 7, {1, Infinity} ]

(* {{1}, {2, 1, 2}, {3}} *)

Get Element by Position

WolframLang List Concepts