Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding to a list defined in a function

How can I create a list in a function, append to it, and then pass another value into the function to append to the list.

For example:

def another_function():
    y = 1
    list_initial(y)

def list_initial(x):
    list_new = [ ]
    list_new.append(x)
    print list_initial

another_function()
list_initial(2)

Thanks!

like image 788
Lance Collins Avatar asked Sep 12 '25 04:09

Lance Collins


1 Answers

I'm guessing you're after something like this:

#!/usr/bin/env python

def make_list(first_item):
    list_new = []
    list_new.append(first_item)
    return list_new

def add_item(list, item):
    list.append(item)
    return list

mylist = make_list(1)
mylist = add_item(mylist, 2)

print mylist    # prints [1, 2]

Or even:

#!/usr/bin/env python

def add_item(list, item):
    list.append(item)
    return list

mylist = []
mylist = add_item(mylist, 1)
mylist = add_item(mylist, 2)

print mylist    # prints [1, 2]

But, this kind of operation isn't usually worth wrapping with functions.

#!/usr/bin/env python

#
# Does the same thing
#
mylist = []
mylist.append(1)
mylist.append(2)

print mylist    # prints [1, 2]
like image 104
MatthewD Avatar answered Sep 14 '25 19:09

MatthewD