View Single Post
Old Dec 25th, 2005, 7:03 PM   #1
UnKnown X
Hobbyist Programmer
 
UnKnown X's Avatar
 
Join Date: Dec 2005
Location: Sandvika, Norway
Posts: 114
Rep Power: 0 UnKnown X is an unknown quantity at this point
Send a message via MSN to UnKnown X
Question about list error

When I try to do something like this:

y = ['1', '2', '3', '4', '5']    # example list
x = []                           # example list 2
i = 0
while i < len(y):
    x.append(y[i])
    i += 1
print x

I get an error message about trying to access an out-of-bounds element of y. This gets fixed if I do this:

y = ['1', '2', '3', '4', '5']    # example list
x = []                           # example list 2
i = 0
while i < len(y) - 1:            # fix is here
    x.append(y[i])
    i += 1
print x

But then, since i only goes to the second last item in y, the programme will only print:
['1', '2', '3', '4']

This is easily fixed by appending an extra item (such as 0) to the end of y, but I'm wondering why this happens.


Edit: wait a second. This list did work. I must've changed something when simplifying from the code from which I took it. Here's where it was originally:

def f(y):
    y.sort()
    y.append('0')
    i, j, k, flag = 0, 0, 0, 0
    x = []
    while j <= 9:
        try:
            while str(y[i]) == str(j) and i < len(y)-1:    # Here's the problem
                flag = 1
                i += 1
                k += 1
        except:
            print "Error!"
            return []
        if flag == 1:
            if k == 1:
                s = str(k) + ' time'
            else:
                s = str(k) + ' times'
            x.append([str(j),s])
        flag, k = 0, 0
        j += 1
    return x

Edit again: Oh, the problem must be in the str(y[i]) part of str(y[i]) == str(j), but still: why?
UnKnown X is offline   Reply With Quote