0

The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.

def skip_elements(elements):
# Initialize variables
new_list = []
i = 0

# Iterate through the list
for element in elements:
    # Does this element belong in the resulting list?
    if elements[i] == element:
        # Add this element to the resulting list
        new_list.append(element)
    # Increment i
    i += 2

return new_list

This is what I tried and it didn't work. Help

  • What does "didn't work" mean? what did it do that you didn't expect? – Sayse Jan 07 '22 at 23:24
  • 1
    In your case, i grows by a factor of two while you are iterating elements at a speed of 1. One simple solution: `new_list = [elements[x] for x in range(0,len(elements),2)]` – C Hecht Jan 07 '22 at 23:25
  • 1
    A hint for you is to check the value of `i` not `element[i]` as `i` is the variable that determines the location and all you need to know is if `i` is a multiple of 2. – MYousefi Jan 07 '22 at 23:30

2 Answers2

1

By incrementing i by 2 for every item in the list you count twice the number of items, so your indexes run outside the list exactly half way to the end.

Instead of counting manually you should use enumerate which will return both index and value for each element.

You should then check if the index is odd or even, by checking the remainder of division by two:

for index, element in enumerate(elements):
    if index % 2 == 0:
        new_list.append(element)
Lev M.
  • 6,088
  • 1
  • 10
  • 23
1

This is what itertools.islice does.

>>> for x in itertools.islice("12345", 0, None, 2):
...   print(x)
...
1
3
5

This special case can be implemented very easily with a generator function:

def skip_elements(itr):
    itr = iter(itr)
    while True:
        yield next(itr)
        next(itr)
chepner
  • 497,756
  • 71
  • 530
  • 681