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()
valueshere), what would we append to?values = []says to Python "I declare that a new object namedvaluesexists and that it's of typelist". Now python knows thatvalueshas a method namedappend()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 likevalues = []and it will figure it out from there.valuesexists and that it's of typelist"—well, not exactly. Python doesn't have type declarations. This creates an empty list via the literal[]and binds that object to the namevalues. It doesn't declare thatvaluesis of typelist.