MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: converting a list element into a number?

  • To: mathgroup at
  • Subject: [mg98628] Re: [mg98585] converting a list element into a number?
  • From: "David Park" <djmpark at>
  • Date: Tue, 14 Apr 2009 06:20:04 -0400 (EDT)
  • References: <23525817.1239608871309.JavaMail.root@n11>

There may be more than one position in an expression that matches a pattern.
And each position may have a multiple level specification. That is why the
result is returned as a list of lists. If there is only one position at the
first level you could use Part to extract its value.

pos = Position[x + y, y]
Part[pos, 1, 1]

Or you could write:

pos = Position[x + y, y]
pos[[1, 1]]

I often use the first form, just to be more explicit and get rid of double

Another good practice in learning, and also in developing code and routines,
is to write multiple steps in one cell. Put each step on a new line (but in
the same cell). You can use % and %% to refer to the output of previous
lines. Then, when you evaluate you can see what each step is doing. Keep
changing, adding and experimenting, each time reevaluating the cell, until
you understand what is happening and you get what you want. If you wish, you
can even interlace the statements with Print statements to annotate what you
think you are doing.

Print["The initial expression"]
expr = x + y
Print["Find the position of y"]
Position[expr, y]
Print["Extract the number using Part"]
Part[%%, 1, 1]
Print["Check it using Part with the position on the expression"]
Part[expr, %%]

You could have multiple statements in a row, some of them with semicolons at
the end if you want to suppress that particular output. With or without the
Print statements this is a really useful way to develop a calculation.

David Park
djmpark at  

From: meitnik [mailto:meitnik at] 

I have noticed when using Position[], it returns a single element
list. So how do I convert that into a number other than using Flatten
to strip off the braces? It seems if I use Flatten within any
subroutine code, I get the error code thats its "Protected". So how do
I work around using Flatten?? Thanks

  • Prev by Date: Re: exponential moving average with a varying exponents.
  • Next by Date: Re: Help with ScriptSource in GUIKit
  • Previous by thread: Re: converting a list element into a number?
  • Next by thread: Bug fixing reporting and fixing rate of Mathematica