Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate randomly a list of 20 elements (elements should be between -50 and 50)

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading