-2

I am trying to have a user input items into a list, and then have all the items they entered go into a list.

Example:

itemList = []
items = input ("Enter all items: ")

What I would like to do is, if user inputs "Test Test2 Test3 Test4", each of the items (seperated by the spaces) gets put into the itemList.

Sorry if I did not explain it very well, and I am not sure if this is even possible.

Thanks in advance

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
dwb
  • 475
  • 6
  • 31
  • You need to visit a tutorial, not ask here. Try https://docs.python.org/3/tutorial/ . `solution = "One Two Three".split()` does what you want. – Patrick Artner Oct 10 '18 at 20:24
  • 1
    `itemList=input ("Enter all items: ").split(" ")` should be enough – mad_ Oct 10 '18 at 20:28
  • @mad_: Typically, you'd omit the argument to `split` entirely. That makes it strip leading and trailing whitespace, and split on runs of whitespace, so having two spaces or a tab between your inputs doesn't add an empty string to your result list in the former case, or fail to split at all in the latter case. – ShadowRanger Oct 10 '18 at 20:48

1 Answers1

0

You want to create a list consisting of the input string, split on spaces (calling "split()" defaults to splitting a string on spaces).

items = input ("Enter all items: ")
itemList = [i for i in items.split()]
print(itemList)

Output, using your suggested input:

['Test', 'Test2', 'Test3', 'Test4']
  • `[i for i in items.split()]` is completely pointless. `items.split()` already returns a `list`, wrapping it in a no-op `list` comprehension just makes a new `list` for no reason. – ShadowRanger Oct 10 '18 at 20:46