简体   繁体   中英

Return a list from a function in Python

I'm new to python so pardon me if this is a silly question but I'm trying to return a list from a function. This is what I have so far but I'm getting nowhere. Can someone tell me what I'm doing wrong here?

I'm trying to make a simple function that called make_a_list(1, 5, "Christian") that returns a list that looks like this: [1, 5, "Christian]

def make_a_list():
    my_list = ["1", "5", "Christian"]
    for item in my_list:
    return my_list

my_list = make_a_list()

print(my_list)

You can do that like this:

def make_a_list(*args):
    return list(args)

print(make_a_list(1, 5, "Christian"))  # [1, 5, "Christian"]

But you do not have to since there is a Python built-in that already does that:

print(list((1, 5, "Christian")))  # [1, 5, "Christian"]

Notice that with the second option you are passing the whole tuple and not the elements separately.

I'm not sure if this is what you want, the question is unclear

def make_a_list(*args):
    def inner():
        return list(args)
    return inner

you would then use it like this

make_list_1 = make_a_list(1, 5, "Christian") # make_list_1 is a function
make_list_2 = make_a_list(2, 10 "A different list") # make_list_2 is a different function

list_1 = make_list_1() # list_1 is a list
print(list_1) # that we can print

In Python you do not need to make a dedicated function to create a list. You can create lists very easily. For example:

list1 = ['one', 'two', 'three']
print(list1)

>>['one','two', 'three']

Check out the following website for more information not only about lists, but other python concepts. https://www.tutorialspoint.com/python/python_lists.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM