Mathematica: Position of elements in a list

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 6K views
Sarah rob
Messages
16
Reaction score
0
If I have a list say
li = {18, 22, 4, 10}
and I want to add for example 7 to this list
Join[li, {7}] to get {18, 22, 4, 10, 7},
can I insert the 7 after the 4, to get {18, 22, 4, 7, 10},
I can't just use Sort[ {18, 22, 5, 10, 7}] as I don' t want to change the order of the whole list?
 
Physics news on Phys.org
http://reference.wolfram.com/mathematica/ref/Insert.html

Insert[list, elem, n]
inserts elem at position n in list. If n is negative, the position is counted from the end.

You might also want to look up the help for Position (so that you can find out what is the position of e.g. 4 in your list).
 
Thanks for that SredniVashtar with regards to position I need to make some kind of rule for n, I tried liss = 7 - li to get {-11, -15, 3, -3}

But I come up with difficulties because if I had 11 -li which gives me {-7, -11, 7, 1} I need to find the position of the smallest positive number
 
Not sure what you are trying to accomplish.
If your list has non-negative numbers only, in the first place, why not using Min to find the smallest entry?

Position[ li , Min[li] ]

Perhaps you have to treat zeros in a special manner?
 
Last edited: