1

I'm trying to get each number that is not 6 into a separate list named valid. With my current knowledge with loops, i try to loop over each element in nums and append into 'valid', but it is not returning ALL NUMBERS that are != 6 (Not 6) even though i'm appending first then deleting the value. My current python version is 3.6

def sum6(nums):
    valid = []

    for item in nums:
        if item != 6:
            valid.append(item)
            nums.remove(item)
        else:
            pass
    print(valid)
    print(nums)

sum6([1,2,3,6,4,5])
  1. Prints valid: [1,3,4] Instead of [1,2,3,4,5]

  2. Prints nums:[2,6,5] Instead of [6]

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Lil boat
  • 119
  • 1
  • 4
  • 14

2 Answers2

2

Here's one way to do this:

def sum6(nums):
    valid = [x for x in nums if x != 6]
    nums = [x for x in nums if x == 6]
    print(valid)
    print(nums)

>>> sum6([1,2,3,4,5,6])
    [1, 2, 3, 4, 5]
    [6]
YOLO
  • 20,181
  • 5
  • 20
  • 40
2

You are changing the nature of the thing that is being iterated on while it's being iterated on. This produces unexpected results, as you've found out. Make a copy of the item for your for loop instead, and keep the specific object you're iterating on intact for the duration of the loop.

So, e.g., maintaining the logical thinking in your code, you would change it to something like this:

def sum6(nums):
    valid = []
    invalid = []
    for item in nums:
        if item != 6:
            valid.append(item)
        else:
            invalid.append(item)
    print(valid)
    print(invalid)

sum6([1,2,3,6,4,5])
Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57