## I can't find the logic error in this bubble sort code

By : Justen
Source: Stackoverflow.com
Question!

I'm attempting to do a simple bubble sort code to get familiar with list/string manip & method use, but for some reason, when I attempt to iterate through each value in the list to remove white space and values that are non ints, it skips some. I haven't even gotten to the bubble sorting part..

``````#test data:  45,5j, f,e,s , , , 45,q,

if __name__ == "__main__":
getList = input("Enter numbers separated by commas:\n").strip()
listOfBubbles = getList.split(',')
print (listOfBubbles)
i = 0
for k in listOfBubbles:
listOfBubbles[i] = k.strip()
print ("i = {0} -- Checking '{1}'".format(i,listOfBubbles[i]))
if listOfBubbles[i] == '' or listOfBubbles[i] == ' ':
del listOfBubbles[i]
i -= 1
else:
try:
listOfBubbles[i] = int(listOfBubbles[i])
except ValueError as ex:
#print ("{0}\nCan only use real numbers, deleting '{1}'".format(ex, listOfBubbles[i]))
print ("deleting '{0}', i -= 1".format(listOfBubbles[i]))
del listOfBubbles[i]
i -= 1
else:
print ("{0} is okay!".format(listOfBubbles[i]))
i += 1

print(repr(listOfBubbles))
``````

Output:

``````    Enter numbers separated by commas:
45,5j, f,e,s , , , 45,q,
['45', '5j', ' f', 'e', 's ', ' ', ' ', ' 45', 'q', '']
i = 0 -- Checking '45'
45 is okay!
i = 1 -- Checking '5j'
deleting '5j', i -= 1
i = 1 -- Checking 'e'
deleting 'e', i -= 1
i = 1 -- Checking ''
i = 1 -- Checking '45'
45 is okay!
i = 2 -- Checking 'q'
deleting 'q', i -= 1
[45, 45, ' ', ' 45', 'q', '']
``````
By : Justen

How about a more pythonic way?

``````#input
listOfBubbles = ['45', '5j', ' f', 'e', 's ', ' ', ' ', ' 45', 'q', '']
#Copy input, strip leading / trailing spaces. Remove empty items
stripped = [x.strip() for x in listOfBubbles if x.strip()]

# list(filtered) is ['45', '5j', 'f', 'e', 's', '45', 'q']
out = []
for val in filtered:
try:
out.append(int(val))
except:
# don't do anything here, but need pass because python expects at least one line
pass
# out is [45, 45]
``````

``````out.sort()
``````

Update To clarify pass

``````>>> for i in range(0,5):
pass
print i

0
1
2
3
4
``````
By : Tom Leys

If you're going to delete from a list while iterating through it, traverse the list in reverse order:

``````for( i = myList.length - 1; i >= 0; i-- ) {
// do something
if( some_condition ) {
myList.deleteItem( i );
}
}
``````

This way you won't skip any list items as shortening the list doesn't affect any future iterations. Of course, the above snippet assumes that the deleteItem method is supported in the list/array class and does the appropriate things.