-1

In the following code, enumerate is skipping every third element in a list.

def skip_elements(elements):
    #k=elements
    for i,j in enumerate(elements):
        print(i,j)
        if i % 2 == 0:
            continue
        else:
            elements.remove(j)

    return elements


print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))  # Should be ['a', 'c', 'e', 'g']
print(skip_elements(
    ['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))  # Should be ['Orange', 'Strawberry', 'Peach']
Guillaume
  • 5,497
  • 3
  • 24
  • 42
  • code:def skip_elements(elements): #k=elements for i,j in enumerate(elements): print(i,j) if i % 2 == 0: continue else: elements.remove(j) return elements print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] print(skip_elements( ['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] – Hemanth Kumar Feb 21 '20 at 12:32

2 Answers2

1

This is happening because you are editing the list elements whilst iterating over it, which will usually cause weird results. You can fix this by using a return list that is separate from the elements list:

Code:

def skip_elements(elements):
    rv = []
    for i,j in enumerate(elements):
        if i % 2 == 0:
            rv.append(j)
        else:
            continue
    return rv

Output:

>>> skip_elements(["a", "b", "c", "d", "e", "f", "g"])
['a', 'c', 'e', 'g']
>>> skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])
['Orange', 'Strawberry', 'Peach']
CDJB
  • 14,043
  • 5
  • 29
  • 55
0

You can also use a list comprehension to create a list with only the items you want inside.

def skip_elements(elements):
    return [v for i, v in enumerate(elements) if not i % 2]
alec
  • 5,799
  • 1
  • 7
  • 20