Home > database >  Function to return list and then clear
Function to return list and then clear

Time:11-09

how could I make my function clear the list and return the inital list on the first execution, and then display a empty list on the second run? I have tried using. Kind regards

def remove():
    items = ["car", "plane", "bus"]
    if len(items) != 0:
        
        return items and items.clear()
    
    
print(remove())
print(remove())
First Print expected output: ["car", "plane", "bus"]
Second Print expected output: []

CodePudding user response:

What you want is not directly possible as items is defined every time the function runs.

Also the None in your output is due to items and items.clear() giving the result of items.clear() which is None.

What might come closest to what you want would be:

# define "items" as a main scope variable
items = ["car", "plane", "bus"]

def remove(items=items):  # or remove(items=["car", "plane", "bus"])
    output = items.copy() # make a copy as items.clear() will clear the object
    items.clear()
    return output
    
print(remove())
print(remove())

output:

['car', 'plane', 'bus']
[]

But honestly, I don't see a good use case for it…

CodePudding user response:

You could make use of the fact that argument defaults are only created once:

def remove(items = ["car", "plane", "bus"]):
    rv = items.copy()
    items.clear()
    return rv

print(remove())
print(remove())

If you want to avoid the extra steps if list is already empty, you can adjust:

def remove(items = ["car", "plane", "bus"]):
    if items:
        rv = items.copy()
        items.clear()
        return rv
    else:
        return items

CodePudding user response:

You have to declare the list outside the function, and declare it in the function as a global variable to modify it.

items = ["car", "plane", "bus"]

def remove():
    global items
    print(items)
    if len(items) != 0:
        items.clear()
        return() 
    
    
remove()
remove()
  • Related