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!
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With