# Generate list of numbers and their negative counterparts

A recent SO question asks for a convenient one-liner to generate a list of numbers and their negative counterparts in Python.

Given two integers $$\1≤a≤b\$$, generate all the integers $$\x\$$ such that $$\a≤|x|≤b\$$. The result may be printed or returned in any order or structure, as putting the result into a list and sorting it, yields [-b,1-b,2-b,…,-a,a,a+1,a+2,…,b]

### Examples

$$\a=6,b=9\$$ gives [6,-6,7,-7,8,-8,9,-9] or [6,7,8,9,-9,-8,-7,-6] or [-8,7,-9,-7,9,8,-6,6] or [[6,-6],[7,-7],[8,-8],[9,-9]] or [[6,7,8,9],[-6,-7,-8,-9]] etc.

$$\a=6,b=6\$$ gives [6,-6] or [-6,6] or [[6,-6]] or [[6],[-6]] etc.

• Semi-related Commented Apr 23, 2020 at 9:29
• Since you seemed to accept concatenated negative numbers in a comment to a certain answer, do you accept 1-1 2-2 3-3 4-4? Commented Apr 23, 2020 at 11:15
• @mypronounismonicareinstate It wasn't just concatenated negative numbers. They were generated as proper numbers, and just printed individually with no separator. That's fine. However, I would object to using string operations to interleave spaces and dashes with duplicated digits, as the individual numbers are never generated then.
Commented Apr 23, 2020 at 11:19
• @HighlyRadioactive By the looks of that Hello world example it can print, so you could print the - characters manually? Commented Apr 24, 2020 at 21:22
• @KevinCruijssen It's not allowed. "However, I would object to using string operations to interleave spaces and dashes with duplicated digits, as the individual numbers are never generated then." -- Adám Commented Apr 25, 2020 at 4:19

# Python 2, 33 bytes

def f(a,b):print-a,a;a<b<f(a+1,b)


Try it online!

A recursive function that prints in a two-column format. Based on ideas from Surculose Sputum.

In Python 3, we'd need 2 more bytes for print() needing parens.

# Python 2, 37 bytes

lambda a,b:range(a,b+1)+range(-b,1-a)


Try it online!

Unfortunately for this challenge, Python's ranges are exclusive, so we have to add 1 to both upper endpoints.

a%b=[a..b]++[-b.. -a]


Try it online!

Looks like this boring solution is shortest. The space in before -a is needed to avoid a misparse with ..-.

22 bytes

a%b=[id,(0-)]<*>[a..b]


Try it online!

22 bytes

a%b=[[x,-x]|x<-[a..b]]


Try it online!

23 bytes

a%b=do x<-[a..b];[x,-x]


Try it online!

23 bytes

a%b=(,)<*>(0-)<$>[a..b]  Try it online! # 05AB1E, 4 bytes ŸD(«  Try it online! # Explanation  Takes two input integers Ÿ Inclusive range. D Duplicate the stack. ( Negate all items of the duplicated item. « Concatenate both lists. Implicit output  # Pyth, 5 bytes _BM}F  Try it online! }F forms an inclusive range, then _B pairs a number with its negation, and M maps that over the list. • _MB}F also works. Commented Jan 18, 2023 at 23:06 # PowerShell, 28 bytes $args[0]..$args[1]|%{$_,-$_}  Try it online! $args[0]..$args[1] generates integer array range from $args[0] to $args[1]. It's piped and then each item in that array is mapped to itself and its negative counterpart. • Welcome to PPCG and great first answer, Eligrhath! Just received your first upvote from me :) Commented Apr 23, 2020 at 11:28 ## Dyalog APL, 19 bytes {(⊢,-)⍺,⍺(⊣+∘⍳-⍨)⍵}  Try it online! • Do you know TIO can auto-generate posts like this one? [Esc],[s],[g]. – Adám Commented Apr 23, 2020 at 8:59 • Welcome to PPCG and great first answer. Who'd have known you're already a very active member of APL Orchard before your first submission! Hope to continue to see you in the room :) Commented Apr 23, 2020 at 11:39 • By the by, this format is also often used in APL TIO links, let me know what you think... I find it convenient for demonstrating all the input cases, when there are several: Click me Even in the case of one input, it can be rather attractive: Peekaboo Commented Apr 23, 2020 at 11:44 • Thank you all for your helpful encouragement. – xpqz Commented Apr 23, 2020 at 11:48 # Python 3, 40 39 bytes -1 byte thanks to @xnor! f=lambda a,b:b//a*[0]and[a,-a]+f(a+1,b)  Try it online! This would be 38 bytes in Python2, by replacing // operator with just /. • Huh, your solution is more competitive that I'd expected for anything recursive here. You can save a byte on the base case, two in Python 2: Try it online! – xnor Commented Apr 23, 2020 at 8:46 • @xnor Ah yes the list multiplication trick. Gotta keep that in mind, thanks! Commented Apr 23, 2020 at 8:51 # Jelly, 3 bytes rNƬ  A dyadic Link accepting two integers (either way around) which yields a list of two lists. Try it online! ### How? rNƬ - Link: integer, a; integer b e.g. 7; 4 r - inclusive range [a..b] [7,6,5,4] Ƭ - collect up while unique, applying: N - negate (vectorises) 0-applications: [[7,6,5,4]] 1-application: [[7,6,5,4],[-7,-6,-5,-4]] 2-applications: [[7,6,5,4],[-7,-6,-5,-4],[7,6,5,4]] - no longer distinct -> [[7,6,5,4],[-7,-6,-5,-4]]  There are many, many ways to achieve this task in four bytes in Jelly. # Ruby, 22 bytes ->a,b{[*-b..-a,*a..b]}  Try it online! # R, 26 25 bytes -1 bytes thanks to Giuseppe function(a,b)c(a:b,-b:-a))  Try it online! # C (gcc), 44 43 42 bytes Saved a byte thanks to ceilingcat!!! Saved a byte thanks to S.S. Anne!!! f(a,b){for(;b/a;)printf("-%d %1$d ",a++);}


Try it online!

# Java 10, 765652 50 bytes

b->a->{for(;a<=b;)System.out.println(a+","+-a++);}


-22 bytes thanks to @OlivierGrégoire.

Takes the inputs in reverse order. Prints pairs of positive and negative integers "a,-a" newline separated.

Try it online.

Explanation:

b->a->{                  // Method with two integer parameters and no return-type
for(;a<=b;)            //  Loop in the range [a,b]:
System.out.println(  //   Print with trailing newline:
a                  //    a
+" "               //    appended with a space
+-a                //    appended with -a
++);}           //   And then increase a by 1 with a++

• Don't know if fully valid, but 72 bytes Commented Apr 24, 2020 at 20:35
• Or 56 bytes. Commented Apr 24, 2020 at 20:41
• @OlivierGrégoire Ah nice, I hadn't thought about just printing directly.. And an additional -1 by removing that space at +++ and -3 by printing directly. I like that Map approach as well btw, very original. :D Commented Apr 24, 2020 at 21:18
• If you take the print route, take it entirely! ;-) I used \n for consistency because of a comment to the question. But one more byte can be gained if you keep the space. Commented Apr 24, 2020 at 21:42
• @OlivierGrégoire Ah nice. :) And space or comma should be fine. OP even allows this kind of output. Commented Apr 24, 2020 at 21:47

# Keg, -pn , 5 bytes

ɧ⑷④±.


It prints all the numbers separated by newlines.

## Explained

ɧ⑷④±.
ɧ      # Generate a range between the two implicit inputs
⑷④±. # For each number in that range, print it raw without popping, negate it, and print it raw


Try it online!

• The challenge says you may print it in any structure, so this is probably okay.
– user92069
Commented Apr 23, 2020 at 8:40
• @petStorm It is.
Commented Apr 23, 2020 at 8:41

# JavaScript (Node.js), 33 31 bytes

-2 bytes thanks to @mypronounismonicareinstate.

b=>f=a=>a>b?[]:[a,-a,...f(a+1)]


Try it online!

• As far as I see, the outermost parentheses aren't necessary (or are they for some reason?) Commented Apr 23, 2020 at 9:24
• @mypronounismonicareinstate thanks for noticing, coming from Python, I just assumed they needed to be there.
– ovs
Commented Apr 23, 2020 at 9:28
• Is the ... necessary?
– l4m2
Commented Jun 11, 2021 at 13:57

# C# (Visual C# Interactive Compiler), 47 46 bytes

Much shorter than the beautiful LINQ solutions with SelectMany :(
I also cannot remember when I last wrote a for loop while code-golfing, so I likely missed trivial golfs.

a=>b=>{for(int i=a;i<=b;Print(-i++))Print(i);}


Try it online!

• You can get rid of i in the for loop. You can also combine the prints. Should be valid according to the challenge. Commented Jan 22, 2023 at 8:43

=ArrayFormula({Row(Indirect(A1&":"&A2));-Row(Indirect(A1&":"&A2))}


Sheets will automatically add the last closing parentheses when you exit the cell. (A 1.5% byte reduction!)

Input is in cells A1 and A2. The order doesn't actually matter.
Indirect(A1&":"&A2) creates a range that contains all the rows between those numbers, inclusive.
Row(Indirect(~)) returns the row numbers of everything in that range.
{Row(~);-Row(~)} creates an array of the positive and negative row numbers.
ArrayFormula(~) makes all the other bits operate on and return arrays. Without this, it would only return the first value in the array (the first row number) instead of all of them.

# PHP, 5146 40 bytes

fn($a,$b)=>[range($a,$b),range(-$b,-$a)]


Try it online!

simply using php7 lambda functions short notation and built-in array functions..

EDIT: hum I see that from PHP7.4 we have now a spread operator! -5 bytes

EDIT2: thanks to DomHastings for saving another 6 bytes!

• Based on the accepted examples, I think you can drop the spreads entirely for -6! Commented Apr 23, 2020 at 13:40
• @DomHastings Oh, yep! Hadn't even looked at the examples :D I was glad to use this new stuff though Commented Apr 23, 2020 at 13:41

# Bash + Core utilties, 21 bytes

seq $1$2;seq -$2 -$1


Try it online!

# LaTeX, 61 56 bytes

\input tikz.tex\def\f#1#2{\foreach~in{#1,...,#2}{~;-~;}}


Defines a macro f that takes input as two arguments and outputs the numbers as tokens to latex (so they are printed in the pdf), semicolon-seperated.

## Explanation

\input tikz.tex                % load the tikz package for the foreach command
\def\f#1#2{                    % define a macro f that takes two arguments
\foreach ~                  % loop with the loop variable called ~
% (to save a space between the name and "in")
in {#1,...,#2} {            % where ~ ranges from the first to the second
% argument, inclusive
~;-~;                  % the macro f expands to
% ~
% a semicolon and a minus sign
% ~
% another semicolon
}
}


## Example

\documentclass{article}
\input tikz.tex
\def\f#1#2{\foreach~in{#1,...,#2}{~;-~;}}
\begin{document}
\f6 9

\f6 6
\end{document}


Output:

• 56 bytes by using \input tikz.tex and looping over ~ instead of \,: \input tikz.tex\def\f#1#2{\foreach~in{#1,...,#2}{~ -~ }} Commented Apr 25, 2020 at 8:06

# Kotlin , 22 bytes

{a,b->(a..b)+(-b..-a)}


# VyxalW, 3 bytes

ṡ:N


Try it Online!

ṡ:N
ṡ       Inclusive range of inputs
:      Duplicate
N     Negate the duplicate

W flag: Wrap both ranges into one list, which is implicitly output


# Erlang (escript), 36 bytes

g(A,B)->[[X,-X]||X<-lists:seq(A,B)].


Try it online!

# Erlang (escript), 40 bytes

g(A,A)->[A,-A];g(A,B)->[A,-A]++g(A+1,B).


Try it online!

# Befunge-98 (FBBI), 24 bytes

&00p&v
0g-k@>::.'-,.1+:0


Try it online!

### Explanation

&00p& is the input part. &00p takes $$\b\$$ as input and stores it in the top left corner. & takes input $$\a\$$ and pushes it to the stack.

0g-k@>::.'-,.1+:0 is the main loop and, as the instruction pointer wraps around, equivalent to:

::.'-,.1+:00g-k@

::                duplicate a twice
.               print a
'-,            print '-'
.           print a
1+         increase a
:        duplicate the new value of a
00g     get b from the top-left corner
-    calculate a-b, as Befunge has no negative values,
this is 0 for b>=a
k@  execute *quit* (b-a)-times


# J, 10 bytes

]-.&i:<:@[


Try it online!

# Husk, 5 bytes

mSe_…


Try it online.

Or alternatively:

Svm_…


Try it online.

Explanation:

    …  # Create a an inclusive range using the two (implicit) input-arguments
m      # Map over this list
Se    # and pair each element with:
_   #  Its negative
# (after which the result is output implicitly)

…  # Create a an inclusive range using the two (implicit) input-arguments
v     # Concatenate it with:
S m    #  The same list with each value mapped to:
_   #   Its negative
# (after which the result is output implicitly)


# Burlesque, 11 bytes

ps^pr@Jng.+


Try it online!

I feel like there's probably a better way to parse the input, but I'm not getting it. Explanation:

ps^p          # Parse input as block and split block to stack
r@        # Generate range between two inputs
Jng     # Duplicate and negate
.+   # Concatenate and implicitly output


# K (oK), 15 bytes

{1 -1*/:y,y^!x}


Try it online!

• Why does {1 -1*,y,y^!x} not work?
Commented Apr 23, 2020 at 12:23
• @Adám K needs instructions (eahright) how to multiply, since the length of both args do not match. Multiplication (as many of the verbs) is right-atomic - it penetrates in depth to the levels of the nesting of the right argument. Commented Apr 23, 2020 at 12:25
• I'm not sure I understand what "right-atomic" means. I just thought that for a scalar function, if one side had one element and the other many, it'd extend the single argument.
Commented Apr 23, 2020 at 12:29
• @Adám Hmm, as it seems * is fully atomic. In our case I'm multiplying a list of length 2 (1 -1) by a list of length 4 (9 6 7 8). I'm not sure why does ' (each) not work here. Commented Apr 23, 2020 at 12:37
• Each-ing with lists of two different lengths is always a length error.
Commented Apr 23, 2020 at 12:38

# brainfuck, 36 bytes

,[->+>->-<<<],+[->>+<<]>>[-<.+>>.-<]


Try it online!

## Clarification

Input and output are treated as bytes (as permitted in Can numeric input/output be in the form of byte values?)

Since negative bytes don't really make sense, a negative answer wraps around and starts at the largest value of the cell. For example, given a cell size of 128, the output for the input in bytes [6, 9] will be (in bytes) [6,(128-6),7,(128-7),8,(128-8),9,(128-9)]

Hopefully that's a fair enough interpretation of the rules!

• i.e. your bytes should be interpreted as 2's complement representations of signed integers. If BF can only actually do I/O in unsigned decimal, that seems fine to me. In assembly language there are no types, it's all just bytes, so it's up to the programmer to to write code that uses signed operations / comparisons on those bytes as opposed to float or unsigned compares. (Many operations other than compare are the same for signed 2's complement vs. unsigned binary integers; division, right shift, and widening mul being different.) Commented Apr 25, 2020 at 1:50

# Perl 5, 20 bytes

say"$_ -$_"for<>..<>


Try it online!

# Zsh, 17 bytes

echo {,-}{$1..$2}


Try it online!