Home > front end >  list comprehension doesn't work with input
list comprehension doesn't work with input

Time:01-01

I am trying to make a plan that allows you to insert strings to a list until you type a certain keyword which then locks the list from further appending.

print("I will list everything you desire!")
list = []
while input("") != "stop":
    shop_list = [list.append(i) for i in input("")]
print(shop_list)
list.clear()

Yet once I run this program, I get an output that has a few issues. output: [None,None] (amount of None is per the number of inputs you give)

In addition to this, after the program finishes running I don't seem to get list cleared. I don't understand why, considering that the clear function should do just as I intend.

Regarding the first problem, I assume it is due to incorrect use of input("") in the extent of list comprehension.

And with the latter issue, I suppose I might have used clear function incorrectly. Although this is how I should use it.

CodePudding user response:

You prob. can try this, as earlier comment pointed out your syntax is off... so it needs to be rewrite and corrected:

Note - in Python 3.8 you can change this line - while (item := input()) != 'stop':


print("I will list everything you desire!")
# L = []
shop_list = []

while True:                    # Loop continuously
    item = input()             # get the input - one item at a time (one line) 
    if item != 'stop':         #  not done yet....
        shop_list.append(item)
    else:
        break
    
print(f' the shop list: {shop_list}')

shop_list.clear()

# Outputs Example:  assuming typing each word by itself (one line each word)
# the shop list: ['apple ', 'orange', 'banana ']
  • Related