Home > Back-end >  How to return object when using `append` in Python
How to return object when using `append` in Python

Time:11-08

i have a function to append a list, something like this:

def append_func(element):
    if xxxx:
        new_list.append(element)
    else:
        []

I have another function that uses append_func():

def second_func(item):
  for i in item:
     append_func(i)

if i run :

new_list = []
second _func(item)
new_list

This will return the list i want, but i can't do new_list = second _func(item) because in this case new_list will be a None.

I understand that append() will return a None type, but i'd like to return the appended list so I can use in other places result = second _func(xxx), what i have missed? Thanks.

CodePudding user response:

simply tell python what to return:

def append_func(element):
    if xxxx:
        new_list.append(element)
    else:
        []
    return new_list   # here, return whatever you want to return

if there is no "return" statement in the function, then the function returns None

CodePudding user response:

The new_list you define before calling second_func is a global variable. Every time you call second_func() it will append the argument to the global variable. But the new_list is not restricted to the namespace of either function, so setting it as a return value doesn't make sense.

CodePudding user response:

According to the clarification you did in the comments you might want something like this. (I changed some of your placeholders so we have running code and a reproducible example)

The list is created by second_func so we get rid of the global list.

def append_func(data, element):
    if 2 < element < 7:
        data.append(element ** 2)


def second_func(items):
    new_list = []
    for i in items:
        append_func(new_list, i)
    return new_list


items = list(range(10))
result = second_func(items)
print(result)

The result is [9, 16, 25, 36].

  • Related