0

I always have a question about the empty list before the for the loop. For example, why do we need to create an empty list value = [] before for token in user_input.split()? When do we need to create such an empty list? Thanks so much for your help.

def get_numbers():
    user_input = input()
    values = []
    for token in user_input.split():
        values.append(int(token))
    return values

def print_selected_numbers():
    numbers = get_numbers()
    for number in numbers:
        if number > 9:
            print(number)

print_selected_numbers()
8
  • 1
    If we didn't have an empty list (named values here), what would we append to? Commented Feb 21, 2022 at 18:13
  • 2
    You have to make an object exist first before you can use a method of that object. Doing values = [] says to Python "I declare that a new object named values exists and that it's of type list". Now python knows that values has a method named append() because it's a list object. In most other programming languages you have to formally declare a variable of a particular type. Declare values as List (psuedocode). Python is much less picky, it just wants you to give it a hint like values = [] and it will figure it out from there. Commented Feb 21, 2022 at 18:14
  • (In this case a list comprehension would be more idiomatic, but when building a list in a loop like this we need a container to put the elements into.) Commented Feb 21, 2022 at 18:14
  • "I declare that a new object named values exists and that it's of type list"—well, not exactly. Python doesn't have type declarations. This creates an empty list via the literal [] and binds that object to the name values. It doesn't declare that values is of type list. Commented Feb 21, 2022 at 18:15
  • @Chris I added to my comment as you were writing that, I think we are saying the same thing. Commented Feb 21, 2022 at 18:16

1 Answer 1

1

As Chris and JNevill noted in the comments to your answer, we need a container that defines an .append method. The empty list is such a container.

As noted by Chris, you can use list comprehension as such:

def get_numbers():
    return [int(token) for token in input().split()]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.