开发者

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!


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 want a list that is scoped to your function, you can do this:

def list_at_function_scope(arg,lst=[]):
    lst.append(arg)
    return lst

print list_at_function_scope(2)
print list_at_function_scope("qwqwe")

And it looks like this:

>>> print list_at_function_scope(2)
[2]
>>> print list_at_function_scope("qwqwe")
[2, 'qwqwe']

Mind you, this is generally regarded as a well-known anti-pattern/error in python. Just so you know what you are getting yourself into.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜