Home > Blockchain >  Building a list by input() python without setting a number of elements
Building a list by input() python without setting a number of elements

Time:04-08

i study python on my own in the middle of an ocean with limited access to internet.

I'm thinking of a way to make a list by input() without setting a number of elements in the beginning. So far i end up with this:

list = []
value = None

while value != '':
    value = input()
    list.append(value)
    if value == '':
        del list[-1]
        break

print(list)

As i can see, code works fine, i can create a list by input(), but it seems ugly to me. I found the way 'With handling exception', but it works only for string or int. Thank you!

CodePudding user response:

Here is a way I would write it:

lst = list()
while True:
  value = input()
  if value == "":
    break
  lst.append(value)

First, use while True to loop forever, with an intention of breaking when certain input is encountered. When value is read, check if it is empty. If so, break. Otherwise, append value to lst and continue with the loop.

By the way, I renamed list to lst to avoid variable shadowing.

CodePudding user response:

Can be written more compactly using the walrus operator (assignment with value):

li = list()
while (val := input()):
    li.append(val)

This saves the input into val and simultaneously evaluates whether it's empty or not, breaking the loop in the former case. It uses the fact that empty strings evaluate to False.

CodePudding user response:

So, assignment expressions were added for this very sort of pattern:

data = []
while (value:= input()):
    data.append(value)

Note the assignment expression "walrus operator" := is only available in Python >= 3.8

Otherwise, you'd generally do something like:

data = []
value = input()
while value:
    data.append(value)
    value = input()

CodePudding user response:

well if you want users to input the element multiple times then the above answers are good. But just say you want an input of elements using a specific separator(space or comma etc) you can do this in one line. eg. if you were to take input using a space as separator, l = [x for x in input().split()] would build your list and if you were to take input and keep , as a separator you could do something like l = [x for x in input().split(sep=",")].

  • Related