0

So lets say I have a a function defined like

def function(x):
    list1 = []
    while list1[-1] < x:
       ... (loop will generate a list of ints)
    return list1

The while loop will generate a list of ints, and I want the while loop to run until the last element of the list being generated is < x.

I tried something like while list1[-1] < x but obviously it returns an error on the first cycle because the list is empty at the beginning and the index is out of range.

spacing
  • 730
  • 2
  • 10
  • 41

1 Answers1

3

Just put a condition if the list is empty in the begin of the loop:

import random
def function(x):
    list1 = []
    while len(list1) == 0 or list1[-1] < x:
        list1.append(random.randint(0,100))
    return list1

print function(100)

[76, 36, 75, 97, 10, 14, 33, 28, 20, 29, 61, 60, 79, 53, 76, 28, 100]

f.rodrigues
  • 3,499
  • 6
  • 26
  • 62