How to return an empty list in python

Viewed 25222

I am trying to call a function that will empty two lists that i send as arguments. How do i go about emptying the lists within the function and making sure they are empty once the code comes to reuse them in the original function in Python? Below is the code i am using as a test run for a larger system.

def Input():
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        ErrorInput(1, nextRound, maleNames )
        # I want the below to print two empty strings
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):


    if error == 1:
        print('ERROR: You have entered a number above what is impossible to 
        score')
        namelist = []
        round = []
    elif error == 2:
        print('ERROR: You Have entered a score meaning both players win')
        namelist = []
        round = []
    elif error == 3:
        print('ERROR: You have entered a score meaning neither of the two 
        players win')
        namelist = []
        round = []
    elif error == 4:
        print('EEROR: You have entered a negative number, this is 
        impossible')
        namelist = []
        round = []

    return(namelist, round)

Input()
3 Answers

Here, I took the liberty to tidy up the code.

def start():  # don't use the name input()
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        nextRound, maleNames = ErrorInput(1, nextRound, maleNames)  # if you want nextRound, maleNames to be [] you have to assign it to them
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):
    error_codes = {1: 'ERROR: You have entered a number above what is impossible to score', 2: 'ERROR: You Have entered a score meaning both players win',3: 'ERROR: You have entered a score meaning neither of the two players win', 4: 'ERROR: You have entered a negative number, this is impossible'}  # too many ifs makes one wonder if a dictionary is the way to go
    print(error_codes.get(error, 'Unknown Error'))
    return([], [])  # return the empty lists.

start()

Not sure why you go to such lengths to just get [], [] but whatever floats your boat.


Take a look at the notes on the code to get a better feeling of why I made the changes.

As per the comment above, i don't follow your code. But to iteratively empty a list try:

while len(maleNames) !=0:
    popped = maleNames.pop()
    print('Popped value: ', popped, '\tNew list: ', maleNames)

Use namelist.clear() to clear a list

Related