-2

I have written the following Python code, but its throwing me an error

    def myfunc(*args):
         mylist = list()
         for num in args:
              if num%2 ==0:
              mylist = mylist.append(num)
        return mylist

It throws me the following error [-2, 4]!= None.

What is wrong with the above code?

Raghu
  • 1,141
  • 5
  • 20
  • 39

5 Answers5

2
mylist = mylist.append(num)

It is a convention in Python that methods that mutate the object return None. list.append is such a function: it will add an element to the list, then return None. By reassignment, your mylist becomes None; which obviously then breaks in the next iteration, as None is not capable of being appended to.

Change the line to just

mylist.append(num)
Amadan
  • 191,408
  • 23
  • 240
  • 301
1

Your code has indent problem. It works fine if you indent it properly. like this:

def myfunc(x):
    mylist = list()
    for num in x:
        if num%2 ==0:
            mylist.append(num)
    return mylist
Usama
  • 42
  • 6
0
def myfunc(*args):
        mylist = list()
        for num in args:
                if num%2 == 0:
                        mylist.append(num)

        return mylist

After correcting indentation and removing assignment of mylist to itself - above code works.

Pravar Jawalekar
  • 605
  • 1
  • 6
  • 18
0
def myfunc(*args):
    mylist = list()
    for num in args:
        if num%2 == 0:
            mylist.append(num)
    return mylist

I think it's because you are using .append in the wrong way.

Giallo
  • 96
  • 4
0

try this!

def myfunc(*args):
    mylist = []
    for arg in args:
        if num % 2 == 0:
            mylist.append(arg)
    return mylist

make sure to call it this way

myfunc(-2, 4)