Home > Mobile >  Type casting errors on a list in python. What is the correct way to make sure this returns as an int
Type casting errors on a list in python. What is the correct way to make sure this returns as an int

Time:10-25

I'm trying to practice my Python on Leetcode. I am having a type casting issue trying to return this as an integer list. From a little research, it appears this might be because I am using "range" in my for loop. Can someone please show me the correct way to do this without it causing an error? Here is my code:

class Solution(object):
def removeElement(self, nums, val):
    for i in range(nums.count(val)):
        nums.remove(val)
    return nums

Here is the error message:

TypeError: [2, 2] is not valid value for the expected return type integer[]
raise TypeError(str(ret)   " is not valid value for the expected return type 
integer[]");
 Line 39 in _driver (Solution.py)
_driver()

Line 45 in (Solution.py)

I get the same error doing it this way too

class Solution(object):
def removeElement(self, nums, val):
    """
    :type nums: List[int]
    :type val: int
    :rtype: int
    """
    while(nums.count(val) != 0):
        nums.remove(val)
    return nums

CodePudding user response:

I figured it out

while loop:

while(nums.count(val) != 0):
        nums.remove(val)
    return len(nums)

for loop:

for i in range(nums.count(val)):
        nums.remove(val)
    return len(nums)

Mark had pointed out the return type should be an int, so I referenced the array as an int and it works. Thanks Mark!

  • Related