Confused: appending to a list

adam.bachman at gmail.com adam.bachman at gmail.com
Thu Mar 23 11:52:35 EST 2006


You're wanting it to stop when the len(list) == 4, right?  The easiest
way to change the logic would be to say

        while len(list) != 4:

but that could get you into trouble later on.  The problem with the
len(list) < 5 expression is that the loop will run "one more time" as
long as len(list) == 4 adding another item to the list giving you one
more than you wanted.  If you wanted, you could put your len() check
inside the loop:

# Start an empty list
list = []
while 1:
    # Get a random number between 1 & 100
    num = random.randint(1,100)
    # Make sure there are no duplicates
    if num not in list:
        # Append each number to the list
        list.append(num)
    if len(list) == 4:
        # Break if we've reached desired length.
        break
print list 

I hope this gives you some ideas.




More information about the Python-list mailing list