-1
a_trial_list = [11, 965, 253, 7]
for i in range(len(a_trial_list) * 2):
    for j in range(i):
        if a_trial_list[j] > a_trial_list[j + 1]:
            a_trial_list[j],a_trial_list[j + 1] = a_trial_list[j + 1], a_trial_list[j]
            a_trial_list.append(1)
    

for x in a_trial_list:
    if x == 1:
        a_trial_list.remove(x)


print(a_trial_list) 

# this code is returning [7, 11, 253, 965, 1, 1, 1, 1, 1]
# it should return [7, 11, 253, 956]

can someone please explain to me why it's not removing the last 1's ???

  • Why `a_trial_list.append(1)`? – Cory Kramer Feb 05 '21 at 12:37
  • 1
    You should read [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating), or [this one too](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – Demi-Lune Feb 05 '21 at 12:38

1 Answers1

0

You can use a try-except clause to handle for Index Errors, instead of appending 1 every time, then removing it. Here is the code:

a_trial_list = [11, 965, 253, 7]
for i in range(len(a_trial_list) * 2):
    for j in range(i):
        try:
            if a_trial_list[j] > a_trial_list[j + 1]:
                a_trial_list[j],a_trial_list[j + 1] = a_trial_list[j + 1], a_trial_list[j]
        except IndexError as e:
            pass

print(a_trial_list)

If you just want to delete the 1 values from the list, you can use the following list comprehension:

a_trial_list[:] = [x for x in a_trial_list if x != 1]
DapperDuck
  • 2,728
  • 1
  • 9
  • 21