[1,2,"-neg",4,"-neg",6] def swapToNeg(lis): for i in lis: if (i " /> [1,2,"-neg",4,"-neg",6] def swapToNeg(lis): for i in lis: if (i " /> [1,2,"-neg",4,"-neg",6] def swapToNeg(lis): for i in lis: if (i "/>

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

79 views Asked by At

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

3

There are 3 answers

2
selbie On BEST ANSWER

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)
3
Coding Dog On

You are not accessing list properly this code works

lis=[1,-2,3]
for i in lis:
  if i<0:
    lis[lis.index(i)]='neg'
0
Sophia Gigliotti On

What you have now is iterating over the items in the list. i is being set equal to 1, 2-3, 4-5 etc. You are receiving the TypeError because when i = 2-3, you change the 6 to the string "neg". then, when i = 4-5, the last element of the list is accessed again, but now i[-1] = "neg". since "neg" is a string, it cannot be compared to an integer. there are a couple of ways to update your function:

  1. you can use range so that i represents the index of each element. i will start as 0 and increase by 1 up until the length of the list. in the for loop, you would need to access lis[i] instead of just i.
def swapToNeg(lis):
    for i in range(len(lis)):
        if (lis[i] < 0):
            lis[i] = "neg"
    print(lis)
  1. you can combine looping over elements and using indices using enumerate. see some documentation here. in the example below el will store the item looped over (1,2-3,4-5...) and i will store the index of the item looped over (0,1,2...).
def swapToNeg(lis):
    for el, i in enumerate(lis):
        if (el < 0):
            lis[i] = "neg"
    print(lis)