Return items from list in function. Python [duplic

2020-02-15 01:56发布

my_list = ['a','b','c']

def func(input):
    for i in input:
        print i
print func(my_list)

Output

a
b
c
None

I don't want the 'None' so how I can do a single line of code to return the items in my input list?

I tried:

return for i in input: print i

but it didn't work because return statements don't work like that

3条回答
▲ chillily
2楼-- · 2020-02-15 02:28

Functions, by default, return None if they come to the end of themselves without returning. So, since there are no return statements in func, it will return None when called.

Furthermore, by using print func(my_list), you are telling Python to print what is returned by func, which is None.

To fix your problem, just drop the print and do:

func(my_list)

Also, if my_list isn't very long, then you don't really need a function at all to do what you are doing. Just use the join method of a string like so:

>>> my_list = ['a','b','c']
>>> print "\n".join(my_list)
a
b
c
>>>
查看更多
Summer. ? 凉城
3楼-- · 2020-02-15 02:32

You are printing the return code from func which is none. Just call func(my_list) without the print.

查看更多
祖国的老花朵
4楼-- · 2020-02-15 02:43

You don't need to call print func(my_list) - just do:

func(my_list)
查看更多
登录 后发表回答