How do I take a specific number of input in python. Say, if I only want to insert 5 elements in a list then how can I do that? I tried to do it but couldn't figure out how.
In the first line I want to take an integer which will be the size of the list. Second line will consist 5 elements separated by a space like this:
5
1 2 3 4 5
Thanks in advance.
count = int(raw_input("Number of elements:"))
data = raw_input("Data: ")
result = data.split(sep=" ", maxsplit=count)
if len(result) < count:
print("Too few elements")
You can also wrap int(input("Number of elements:")) in try/except to ensure that first input is actually int.
p.s. here is helpful q/a how to loop until correct input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With