4
$\begingroup$

How can I convert a list such as:

a = {1, 2, 0.1}

into sequence so that I can pass them into a function, e.g. I want to be able to do something like this

Range[a]

so that the output will be:

1, 1.1, 1.2, ... , 2.0

$\endgroup$
  • $\begingroup$ I modified the title to make it a bit more informative and added some formatting - for your next questions please have a look at the FAQ and the markdown help. $\endgroup$ – Yves Klett Feb 22 '13 at 7:20
8
$\begingroup$

You can use the Range function in this way:

Range[1, 2, 0.1]

to get

{1.,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.}

If the problem is how to pass the parameter a you can use:

1- Using Apply.

a = {1, 2, 0.1}
Range@@a

The Apply operator (@@) "decapitates" the List head from list a and changes it by Range.

2- Using Sequence

a = {1, 2, 0.1};
Range[Sequence @@ a]

It's useful when you have another variables to pass. That's not your case, but I just wrote to be more didactical.

$\endgroup$
  • $\begingroup$ Thank you! That is exactly what I wanted. $\endgroup$ – Raj Feb 22 '13 at 0:12
4
$\begingroup$

Taking the last line of the question even more literally than Mr.Wizard

a = {1, 2, 0.1};
r = Range @@ a;
Row[{Sequence @@ r[[1 ;; 3]], "...", r[[-1]]}, ","]

1., 1.1, 1.2, ..., 2.

$\endgroup$
  • 1
    $\begingroup$ The audacity! +1 :-) $\endgroup$ – Mr.Wizard Feb 22 '13 at 7:21
  • $\begingroup$ you need to go 1 level more literal and implement the cream bg with an orange dotted border on the left :D $\endgroup$ – rm -rf Feb 22 '13 at 7:26
  • $\begingroup$ @rm-rf that wasn't in the original or it would have been really funny. $\endgroup$ – Mr.Wizard Feb 22 '13 at 7:36
3
$\begingroup$

... you can also use ReplaceAll:

 a={1,2,.1};
 a /. List->Range (* ReplaceAll *)
 (* {1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.} *)

or, ReplacePart:

 ReplacePart[a, 0 -> Range]
 (* {1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.} *)

or, set Part zero to Range (re-assign head):

 b=a; b[[0]]=Range;b
$\endgroup$
  • $\begingroup$ +1 for symbol[[0]]=newHead. $\endgroup$ – Murta Feb 22 '13 at 10:21
2
$\begingroup$

Taking the last line of your question literally:

a = {1, 2, 0.1};

Row[Range @@ a, ","]
1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.

Also, to illustrate an alternative data format:

a = Sequence[1, 2, 0.1]

Range[a]
{1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.}
$\endgroup$
  • $\begingroup$ Thanks, that's also very useful to know for future use. As you can probably tell, I'm a newbie. $\endgroup$ – Raj Feb 22 '13 at 0:39
1
$\begingroup$

Also

a = {1, 2, 0.1};
Table[i, {i, ##}] & @@ a

(*{1., 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.