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

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…

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

>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)
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