[SOLVED] How come when adding items into my list, inside a function, I need to put the element I'm adding in brackets?

Issue

def myfunc(*args):
    mylist = []
    for num in args:
        if num % 2 == 0:
            mylist += [num]
        else:
            pass
    return mylist

In the example above, (my list += [num]), how come num has to be inside brackets? Using Thonny I finally figured out I needed to do this, but I still don’t know why. It seems like it should just add the num to the list (in my brain)? Appreciate any help.

Solution

When you use += to add it looks to combine variables of similar type, so num can be added to another int or float, but only list can be added to a list.

num = 2
num += 2
test = []
test += [4]
print(num, test)

Output:

4 [4]

You can also use list.append() if you want:

def myfunc(*args):
    mylist = []
    for num in args:
        if num % 2 == 0:
            mylist.append(num)
        else:
            pass
    return mylist
print(myfunc(1,2,3,4,5,6))

Output:

[2, 4, 6]

This adds num as a element directly.

Answered By – Eli Harold

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.