# Assign values in a list and ignore certain ones

Let's say that I have a function which returns a list of values (the length of the list is n). But, let's also say, that I am only interested in the first two returning values, or last two. My question is, how to ignore the rest of the list? To give an example, one can imagine already a list like this:

mylist={a,b,c,d,e,f};


To simulate my situation, I want to do:

{x,y,(* ignore the rest *)} = mylist


or

{(* ignore this *), (* ignore this *), x, y, (* ignore the rest *)} = mylist


I thought the use of blanks would work but it does not:

{x,y,_} = mylist


and neither

{x,y,_z} = mylist


I know I could probably simply do:

{x,y}=mylist[[1;;2]]


and so on, but I was wondering, if there is a symbol that can be used to dump all the unwanted parts of list that would also take care of dimensionality problem.

• I don't think there is an "unpacking" syntax for this. I just use {x,y} = Take[result, 2]. – Szabolcs Oct 11 '16 at 14:02

mylist = {a, b, c, d, e, f}


$\{a,b,c,d,e,f\}$

In doing so, you take only the first two values

{x, y} = Take[mylist, 2]


$\{a,b\}$

In doing so, you take only the last two values

{x, y} = Take[mylist, -2]


$\{e,f\}$

When you do this, you only take the value of the desired position with the following

pos = 3;
Take[mylist, {pos, pos + 1}]


$\{c,d\}$

Using Part

Part[mylist, ;; 2]


{a, b}

Part[mylist, -2 ;;]


{e, f}

Part[mylist, 3 ;; 4]


{c, d}

Every second value

Part[mylist, ;; ;; 2]


{a, c, e}

I am not aware of any established "write-only" mathematica variable.

But, technically, you can use any variable you dislike as "trash", that is if you don't mind the value staying in RAM. Mathematica will even let you use the same variable multiple times:

myfunc[___]:={1,2,3,4,5};


You can put values #3-#5 into "trash" variable

{a,b,X,X,X} = myfunc["args..."];


Values #3-#4 will be forgotten immediately. #5 will stay in "trash" until overwritten.

{a,b,X,X,X}


$$\{1,2,5,5,5\}$$

The "proper Mathematical way" to ignore values in a list is Take or Part, as explained in the other answers. But I see how this feature would be useful to enforce the list lenght or shape "API".

• PS: Which language does use _ for this purpose? Python? Perl? How do they call this feature? – user185953 May 31 at 8:16
• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Michael E2 May 31 at 12:43