Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate list of numbers and their negative counterparts in Python

Is there a convenient one-liner to generate a list of numbers and their negative counterparts in Python?

For example, say I want to generate a list with the numbers 6 to 9 and -6 to -9.

My current approach is:

l = [x for x in range(6,10)] l += [-x for x in l] 

A simple "one-liner" would be:

l = [x for x in range(6,10)] + [y for y in range(-9, -5)] 

However, generating two lists and then joining them together seems inconvenient.

like image 487
upe Avatar asked Apr 21 '20 16:04

upe


People also ask

How do you print negative values in a list Python?

Python3. Example #1: Print all negative numbers from the given list using for loop Define start and end limit of the range. Iterate from start till the range in the list using for loop and check if num is less than 0. If the condition satisfies, then only print the number.

How do you get negative values in Python?

Python Code:n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero! ") else: print("Number is Positive number. ") else: print("Number is Negative number. ")

How do you make all elements in a Python array negative?

negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar. Parameters : arr : [array_like or scalar] Input array.

How are negative numbers represented in Python?

Negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your twos-complement numbers, then you treat patterns from "00000000" to "01111111" as the whole numbers from 0 to 127, and reserve "1xxxxxxx" for writing negative numbers.


2 Answers

I am unsure if order matters, but you could create a tuple and unpack it in a list comprehension.

nums = [y for x in range(6,10) for y in (x,-x)] print(nums) [6, -6, 7, -7, 8, -8, 9, -9] 
like image 192
Umar.H Avatar answered Oct 26 '22 03:10

Umar.H


Create a nice and readable function:

def range_with_negatives(start, end):     for x in range(start, end):         yield x         yield -x 

Usage:

list(range_with_negatives(6, 10)) 

That is how you get a convenient one-liner for anything. Avoid trying to look like a magic pro hacker.

like image 30
Derte Trdelnik Avatar answered Oct 26 '22 04:10

Derte Trdelnik