[Tutor] modification to a list

Mats Wichmann mats at wichmann.us
Sat Apr 25 12:33:21 EDT 2020


On 4/24/20 10:03 PM, Subhash Nunna wrote:
> Hi Shubham,
> 
> 
> Here is the code meeting you’re conditions:
> def skip_elements(elements):
>               # Initialize variables
>               new_list = []
>               i = 0
> 
>               # Iterate through the list
>               for i,element in enumerate(elements):
>                            # Does this element belong in the resulting list?
>                            if elements.index(element)%2==0:
>                                          # Add this element to the resulting list
>                                          new_list.append(element)
>                            # Increment i
>                            i += 1
> 
> 
>               return new_list
> 
> 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']
> print(skip_elements([])) # Should be []


This question illustrates a difficulty that faces those of us answering
on tutor.  In many cases an assignment (homework problem, exercise in a
book, etc.) intends you to use something specific because at that moment
in time the curriculum wants you to learn about that specific feature.
Of course you need to practice how to step through a list in a loop,
it's a skill a Pythoneer absolutely must have.  But we _also_ want you
to learn effective Python, and this problem has, as Mark has already
suggested a while ago, a simpler approach available because it's
something people need to do often.  So in the spirit of the latter (and
presumably not the wanted answer in this case), this is a solution to
the actual problem:

def skip_elements(elements):
    return elements[::2]

In the list "slicing" notation we have

starting-index:stop-index:stepsize

where for the start and stop indices, and omitted value means
"beginning" and "end" respectively.

Here is that pasted into an interactive interpreter:

>>> def skip_elements(elements):
...     return elements[::2]
...
>>> print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
['a', 'c', 'e', 'g']
>>> print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi',
'Peach']))
['Orange', 'Strawberry', 'Peach']
>>> print(skip_elements([]))
[]
>>>




More information about the Tutor mailing list