I need to display the list on the screen. With
use of the list generator generate a new list based on it, in
which double the negative elements. Output a new list to
screen.
The first list outputs normally, without any problems. But I have an error with the displaying of the second list.
import random
c = 0
x = [ (random.randint (-50, 50) ) for c in range (20)]
print ('First list:', x)
y = [x * 2 (random.randint (-50, 50) ) for c in range (20) if x < 0]
print ('Second list:', y )
>Solution :
You could use an if statement to determine to filter only the negative elements you want to double:
from random import randint
x = [randint(-50, 50) for _ in range(20)]
print(f'{x = }')
# If you want to keep only the doubled negative elements
y = [n * 2 for n in x if n < 0]
print(f'{y = }')
# If you want to keep the non negative elements as well you can use an if-else
z = [n * 2 if n < 0 else n for n in x]
print(f'{z = }')
Example Output:
x = [-2, -31, 35, -3, -34, 47, 28, 34, -18, 26, -25, -48, 18, -30, 1, 48, 43, -29, -30, -22]
y = [-4, -62, -6, -68, -36, -50, -96, -60, -58, -60, -44]
z = [-4, -62, 35, -6, -68, 47, 28, 34, -36, 26, -50, -96, 18, -60, 1, 48, 43, -58, -60, -44]