![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Hobbyist Programmer
|
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 xI 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 xBut 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 xEdit again: Oh, the problem must be in the str(y[i]) part of str(y[i]) == str(j), but still: why? |
|
|
|
|
|
#2 |
|
Hobbyist Programmer
|
Ah, problem found.
In str(y[i]) == str(j) and i < len(y)-1, it would check whether str(y[i]) == str(j) after i had been incremented, but before it could check if i < len(y), thus it would go beyond the list's boundary. Putting the i < len(y) test before the str(y[i]) == str(j) test fixed it. ![]() |
|
|
|
|
|
#3 |
|
Expert Programmer
|
Nice job :-)
__________________
Join us at #programmingforums @ irc.freenode.net! My software never has bugs. It just develops random features.
|
|
|
|
|
|
#4 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5
![]() |
You might want to think about using a dictionary to hold the counts of your items:
d = {}
for x in y:
d[x] = d.get(x, 1) + 1bag = {}
for item in list:
bag[item] = bag.get(item, 1) + 1 |
|
|
|
|
|
#5 |
|
Hobbyist Programmer
|
Thanks for the replies!
I was simply doing this as a test. In slightly more serious projects, I do use more descriptive names. I'll try the dictionaries, too. Thanks! |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|