How to stop placing elements in list

Viewed 72

I want te creates a function which add elements to list. I want it to stop when it comes to border of range() I got this:

def get_values(i,n):
  d =[]
  for x in range(n):
      d.append(next(i))
  return d

i = iter(range(10))

print((get_values(i,5)))
print((get_values(i,4)))
print((get_values(i,2)))

It gives me:
[0, 1, 2, 3, 4]
[5, 6, 7, 8]
Traceback (most recent call last):
  File "/Users/user/Documents/untitled1/lol.py", line 17, in <module>
    print((get_values(i,2)))
  File "/Users/user/Documents/untitled1/lol.py", line 4, in get_values
    d.append(next(i))
StopIteration

But I want to achive this:

>>> i = iter(range(10))
>>> get_values(i, 3)
[0, 1, 2]
>>> get_values(i, 5)
[3, 4, 5, 6, 7]
>>> get_values(i, 4)
[8, 9]
>>> get_values(i, 4)
[]

How can I control the loop to put just elements from range() of i?

3 Answers

just listen to the error and stop iteration when there is a error and break out of the loop:

def get_values(i,n):
  d =[]
  for x in range(n):
      try:
          d.append(next(i))
      except StopIteration:
          break
  return d

The only way you can check if you can continue is to listen to the StopIteration exception. Here is another solution I thought can be handy:

def get_values(i, n):
    d = []
    try:
        for _ in range(n):
            d.append(next(i))
    finally:
        return d

Look for https://www.geeksforgeeks.org/python-next-method/ to learn more about arguments you can pass to next statement

def get_values(i,n):
  d =[]
  for x in range(n):
      temp=next(i,'end')
      if temp=="end":
          break
      d.append(temp)
      
  return d
i = iter(range(10))

print((get_values(i,5)))
print((get_values(i,4)))
print((get_values(i,2)))

Output

[0, 1, 2, 3, 4]
[5, 6, 7, 8]
[9]
Related