Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

 
 
Thread Tools Display Modes
Prev Previous Post in Thread   Next Post in Thread Next
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
 

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 5:37 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC