Find negative Numbers in list and change | Python

Question:

I want to sort out all Numbers under 0 in a List and add to the numbers under 0 + 500.

import random
from turtle import st

startFrame = random.randint(0, 200)

print(startFrame)

start = []

for i in range(startFrame -125, startFrame):
    
    start.append(i)

print(start)

for Frame in start:
    
    if Frame > 0:
        
        Frame + 500
        
print(start)

Did anyone can find out why its not working?

Asked By: D3rs

||

Answers:

Just do the following:

for i in range(len(start)):
    if start[i] < 0:
        start[i] += 500
print(start)
Answered By: Nick

You need to save your addition in a new list and output that.

import random
from turtle import st

startFrame = random.randint(0, 200)

print(startFrame)

start = []

for i in range(startFrame -125, startFrame):
    
    start.append(i)


print(start)

start2 =[]
for Frame in start:
    
    if Frame < 0:
        
        start2.append(Frame + 500)
        
        
print(start2)
Answered By: 24thDan

The adjustment to your Frame variable has no effect on the list contents.

You could do this:

from random import randint
    
r = randint(0, 200)
start = list(map(lambda x: x if x > 0 else x + 500, range(r-125, r)))
print(start)
Answered By: Stuart
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.