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

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

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 :

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

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.

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