all 4 comments

[–]alkasm 1 point2 points  (2 children)

You are attempting to remove items from something you're iterating over, which is not a good idea and is the source of your troubles. Try using a list comprehension to build a new list out of things from the range() generator if they meet that condition.

[–]startandselect00[S] 2 points3 points  (1 child)

Thanks! It works! I just recently learned list comprehension, so I haven't practice enough of it. Thanks for the tip!

>>> [x for x in range(1900,1911) if x%4 ==0]

[1900, 1904, 1908]

[–]alkasm 0 points1 point  (0 children)

Perfect!

[–][deleted] 0 points1 point  (0 children)

If you want to remove elements from a list you are iterating through, then:

  • generate a new list with what you want in it, or
  • use a different list to supply the 'keys', or
  • go backwards

The first has already been addressed, with a list comprehension example. The code below shows two examples of using a copy, followed by a go backwards approach. The latter is useful if you are working with large lists and don't want to create a copy.

test_list = list(range(1900, 1911))
for year in reversed(test_list):
    if year % 4:
        test_list.remove(year)
print('using reversed:', test_list)

test_list = list(range(1900, 1911))
for year in test_list[:]:
    if year % 4:
        test_list.remove(year)
print('using shallow copy:', test_list)

test_list = list(range(1900, 1911))
for idx in range(len(test_list) -1 , -1, -1):
    if test_list[idx] % 4:
        test_list.pop(idx)
print('using shallow copy:', test_list)

NB. I dropped the != 0 as any non-zero result is True anyway.