Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string input and append to a list? Python

I want to ask the user what foods they have ate, then split that input up into a list. Right now, the code is spitting out just empty brackets.

Also, this is my first post on here, so I apologize in advance for any formating errors.

list_of_food = []


def split_food(input):

    #split the input
    words = input.split()

    for i in words:
        list_of_food = list_of_food.append(i)

print list_of_food
like image 798
ItAintRocketSurgery Avatar asked Oct 23 '25 00:10

ItAintRocketSurgery


1 Answers

for i in words:
    list_of_food = list_of_food.append(i)

You should change this just to

for i in words:
    list_of_food.append(i)

For two different reasons. First, list.append() is an in-place operator, so you don't need to worry about reassigning your list when you use it. Second, when you're trying to use a global variable inside a function, you either need to declare it as global or never assign to it. Otherwise, the only thing you'll be doing is modifying a local. This is what you're probably trying to do with your function.

def split_food(input):

    global list_of_food

    #split the input
    words = input.split()

    for i in words:
        list_of_food.append(i)

However, because you shouldn't use globals unless absolutely necessary (it's not a great practice), this is the best method:

def split_food(input, food_list):

    #split the input
    words = input.split()

    for i in words:
        food_list.append(i)

    return food_list
like image 84
TheSoundDefense Avatar answered Oct 25 '25 14:10

TheSoundDefense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!