Python Forum
weird result trying to remove numbers from a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
weird result trying to remove numbers from a list
#2
You are modifying a list that you are looping through. Here's an idea of what is happening:
  • Start at position 0 with value 1
  • Remove element at position 0, all following elements are shifted back by one
  • Continue at position 1 with value 3 (you skipped over 2)
  • Remove element at position 1, all following elements...
  • Continue at position 2 with value 5 (you skipped over 4)
  • Remove element at position 2, ...
  • All following elements are preserved because they do not meet the if test.
One solution is to create an empty list and append to it all elements that you would not remove from the original list:
both = nums + words
new_list = []

for each in both:
    if each not in range(1000):
        new_list.append(each)
I haven't tested this but it should do the trick.
Reply


Messages In This Thread
RE: weird result trying to remove numbers from a list - by boring_accountant - Aug-21-2019, 02:02 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 450 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 8 15,704 Jan-05-2024, 08:30 PM
Last Post: sgrey
  regex findall() returning weird result Radical 1 649 Oct-15-2023, 08:47 PM
Last Post: snippsat
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,249 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  List of random numbers astral_travel 17 2,719 Dec-02-2022, 10:37 PM
Last Post: deanhystad
  Remove numbers from a list menator01 4 1,343 Nov-13-2022, 01:27 AM
Last Post: menator01
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,526 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  set.difference of two list gives empty result wardancer84 4 1,507 Jun-14-2022, 01:36 PM
Last Post: wardancer84
  Divide a number by numbers in a list. Wallen 7 8,043 Feb-12-2022, 01:51 PM
Last Post: deanhystad
  Remove empty keys in a python list python_student 7 3,048 Jan-12-2022, 10:23 PM
Last Post: python_student

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020