Python Forum
Why does modifying a list in a for loop not seem to work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does modifying a list in a for loop not seem to work?
#1
Question 
numbers = [2,8,6,12,13,9,5]
for number in numbers:
    if number % 2 == 0 :
        numbers.remove(number)
print(numbers)
I wrote that code and run it .But it should delete all the even numbers in the list. But it left some of them .Please check it and give me a solution.
Huh Huh Huh
Reply
#2
you should not modify numbers while iterating over it

numbers = [2,8,6,12,13,9,5]
odd_numbers = []
for number in numbers:
    if number % 2: # number is odd
        odd_numbers.append(number)
print(odd_numbers)
or simply
numbers = [2,8,6,12,13,9,5]
odd_numbers = [number for number in numbers if number % 2]
print(odd_numbers)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  While Loop Does Not Work Properly mactron 4 871 Jun-22-2023, 01:04 AM
Last Post: mactron
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,256 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Beginner: Code not work when longer list raiviscoding 2 763 May-19-2023, 11:19 AM
Last Post: deanhystad
  How to work with list kafka_trial 8 1,940 Jan-24-2023, 01:30 PM
Last Post: jefsummers
  For Loop Works Fine But Append For Pandas Doesn't Work knight2000 2 1,929 Dec-18-2021, 02:38 AM
Last Post: knight2000
  Modifying code cheburashka 1 1,253 Dec-13-2021, 01:01 PM
Last Post: Kebap
  How can this for loop work without : ? Pedroski55 1 1,673 Dec-13-2020, 01:19 AM
Last Post: palladium
  Please help my while loop does not work as expected KingKhan248 6 2,561 Sep-28-2020, 09:12 PM
Last Post: deanhystad
  Appending to list of list in For loop nico_mnbl 2 2,318 Sep-25-2020, 04:09 PM
Last Post: nico_mnbl
  Append list into list within a for loop rama27 2 2,307 Jul-21-2020, 04:49 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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