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.
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.
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. ")
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.
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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With