# How do I find the elements inside a list using another list?

Let's say I have a long expression which contains many x. I want to see where all the x are so I do pos=Position[expr, x, Infinity] and I find something like

{{1, 5, 1, 1}, {1, 5, 1, 2}, {1, 6, 1, 1}, {1, 8, 1, 2, 1}, {1, 8, 1, 3, 2, 1,
2, 2, 1}, {1, 8, 1, 3, 2, 2, 1}, {1, 8, 1, 3, 2, 3, 1, 2, 2, 1}, {1,
10, 1, 1, 3, 1, 1, 2, 1}, {1, 10, 1, 1, 3, 1, 1, 3, 2, 1, 2, 2,
1}, {1, 10, 1, 1, 3, 1, 1, 3, 2, 2, 1}, {1, 10, 1, 1, 3, 1, 1, 3, 2,
3, 1, 2, 2, 1}, {1, 10, 1, 2, 1, 1, 2, 1}, {1, 10, 1, 2, 1, 1, 4,
2, 1, 2, 2, 1}, {1, 10, 1, 2, 1, 1, 4, 2, 2, 1}}

I want to see which types of expressions contain an x, for example, the x could be inside (x-y)^2 or y/x or whatever. So I do posit = Drop[#, -1] & /@ pos and I have my list with all the positions of the expressions containing and "x". This is fine. If I type expr[[1,5,1]] or expr[[{1},{5},{1}]] I can do that by hand. But I don't want to do that for every case in posit, I want to do something like

Table[expr[[posit[[i]]]], {i, 1, Length[posit]}] and see a table with all the cases that contain x.

But if do this what I am doing is expr[[{1,5,1}]] and Mathematica doesn't show the position [[1,5,1]] of expr but rather the position 1, the position 5 and the position 1 again of the whole expr.

How do I remove the brackets of {1,5,1} so I can have expr[[1,5,1]] by taking all the elements in the list posit?

expr = {Nest[foo, x/y, 5], 2, x^2 + y, 3 x, 1/x + y, 5}
{foo[foo[foo[foo[foo[x/y]]]]], 2, x^2 + y, 3 x, 1/x + y, 5}
pos = Position[expr, x, Infinity]
{{1, 1, 1, 1, 1, 1, 1}, {3, 1, 1}, {4, 2}, {5, 1, 1}}
posit = Drop[pos, None, -1]
{{1, 1, 1, 1, 1, 1}, {3, 1}, {4}, {5, 1}}

You can get the desired result in several ways:

Table[expr[[Sequence @@ posit[[i]]]], {i, 1, Length[posit]}] (* or *)

Table[expr[[Sequence @@ i]], {i, posit}] (* or *)

expr[[##]] & @@@ posit (* or *)

Extract[expr, posit]

all give

{x/y, x^2, 3 x, 1/x}

Alternatively, you can use Cases to get the desired result in a single step:

Cases[expr, _[___, x, ___], All]
{x/y, x^2, 3 x, 1/x}