spacing
spacing

Reputation: 780

Use the resultant list of a while loop as a condition for the loop itself

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.

Upvotes: 0

Views: 63

Answers (1)

f.rodrigues
f.rodrigues

Reputation: 3587

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]

Upvotes: 3

Related Questions