Home > Net >  Why can't I use the split() method in Python to split a string into a list from within a functi
Why can't I use the split() method in Python to split a string into a list from within a functi

Time:10-30

I am unable to split a string into a list using a function in Python. However, when I do it without a function, it works. Here's my code:

def listAdder(list1):
    """ Function to split a string into a list. """
    text_line = "This is a string"
    list1 = text_line.split(' ')
    print(list1)    # printing the list to verify its status within the function.

list1 = []
listAdder(list1)
print(len(list1))    # printing the length of the list to verify its status outside the 
                     # function

The output:

['This', 'is', 'a', 'string']
0

The list is successfully created with the string elements split inside it within the function, as is evident from the output. However, the list remains empty when I try to verify its state out of the function.

What do I need to do to make the list retain its value outside the function?

CodePudding user response:

You have to assign the updated list (by your function) to another variable in your main program, like below. Inside the listAdder function only a copy of the list1 variable declared in your main program body is modified, that change will not reflect in main body unless you return a copy of it from your function.

def listAdder(list1):
    text_line = "This is a string"
    list1 = text_line.split(' ')
    print(list1)    # printing the list to verify its status within the function.
    return list1

list2 = listAdder(list1)
print(len(list2))

CodePudding user response:

This is because of the scope of variables. Updating list1 in the function does not update that object outside the scope of the function.

You can use a function without parameters and mark it with global list1, which allows it to alter list1 that you have declared in the global scope.

def listAdder():
    global list1 # This allows it to modify the variable
    """ Function to split a string into a list. """
    text_line = "This is a string"
    list1 = text_line.split(' ')

list1 = []
listAdder() # No parameter
print(len(list1)) # Prints 4

This is considered poor practice, however, as it can be harder to reason about our code.

It is better to use a function to return a value.

def listAdder():
    text_line = "This is a string"
    return text_line.split(' ')

list1 = []
list1 = listAdder()
  • Related