0

I want to fill a list with n integers in a single line, I tried this but how to add a limit of n?

L=[int(x) for x in input().split()]
martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

2

zip stops on the shortest sequence. You can use that to limit how many split items you consume.

limit = 5
L=[int(x) for _,x in zip(range(limit), input().split(maxsplit=limit))]
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Great answer for what it's worth – Chris Jan 07 '21 at 19:04
  • The downvote is really a mystery as this is actually better than the other solutions because they create two lists... This only creates one in the exact right size (both `zip` and `range` are iterators...) – Tomerikoo Jan 07 '21 at 19:09
  • adding `maxsplit=limit` to your code yields another 20x improvement on a 10MM int list. Something like `[int(x) for _,x in zip(range(limit), input.split(maxsplit=limit))]` where `input= ' '.join(([str(x) for x in range(10000000)])` – Chris Jan 07 '21 at 19:16
  • @Chris = `[int(x) for x in "1 2 3 4 5 6".split(maxsplit=3)]` results in `ValueError: invalid literal for int() with base 10: '4 5 6'`. – tdelaney Jan 07 '21 at 19:21
  • @Tomerikoo - right, and in other cases where the second thing in `zip` is a generator, it short circuits, so its a good general purpose solution. – tdelaney Jan 07 '21 at 19:22
  • @tdelaney don't need to preach the preacher, already got my +1 ;) – Tomerikoo Jan 07 '21 at 19:24
  • 1
    @tdelaney You have to use that in conjunction with your zip to terminate the process before the last unsplit digits – Chris Jan 07 '21 at 19:24
  • Still, regarding your last comment to me, check this out: https://stackoverflow.com/questions/3862010/is-there-a-generator-version-of-string-split-in-python you ***can*** have a generator as the second argument to `zip` :D That would be minimal memory use on this page :) – Tomerikoo Jan 07 '21 at 19:27
1

Just slice at the limit.

limit = 3
L = [int(x) for x in input().split()][:limit]
Chris
  • 15,819
  • 3
  • 24
  • 37
0

Does this work?

n=int(input())
while True:
  L=[int(x) for x in input().split()]
  if len(L)==n:
     break
  • Why are you asking us? you should know... By the way if this is an online coding challenge, most chances are that you don't actually need to do this as the input will come in the expected format... – Tomerikoo Jan 07 '21 at 19:33