pythonstringlistnegative-number

Python: swapping negative numbers on a given list to a string


Given a list of numbers swap any negative num with the string "neg" [1,2-3,4-5,6 ] => [1,2,"-neg",4,"-neg",6]

def swapToNeg(lis):
    for i in lis:
        if (i < 0):
            lis[i] = "neg"
    print(lis)

I keep running into 2 types of errors that I cant seem to figure out. --> 1 - IndexError: list assignment index out of range --> 2 - TypeError: '<' not supported between instances of 'str' and 'int'

How can you change the number to a string by accessing the index manually but cant change a number to string when you iterate through it compare and change??? this is eating me up...


Solution

  • You're trying to use i as both the list index and the value at that index in the list. For the for loop you've constructed just iterates over values, not incremental indices.

    You probably want something like this where you iterate over index values. You can use the range operator to enumerate from 0..len(lis)-1

    def swapToNeg(lis):
        list_length = len(lis)   
        for i in range(list_length):
            if (lis[i] < 0):
                lis[i] = "neg"
        print(lis)