[Tutor] modification to a list
Mark Lawrence
breamoreboy at gmail.com
Wed Apr 22 11:11:26 EDT 2020
On 22/04/2020 15:44, shubham sinha wrote:
> Hi,
> Q. 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.
> my code:
> def skip_elements(elements):
> new_list = [ ]
> i = 0
> for element in elements:
> if "element" != "elements(i):
> new_list.append(element)
>
> i += 2
> return new_list
You don't need any of the above code, you can do the entire operation in
one hit with the use of slicing as given here
https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
which I'll leave up to you as an exercise :)
>
> 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 [ ]
>
> my output:
>
> ['a', 'b', 'c', 'd', 'e', 'f', 'g']
> ['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']
> []
>
>
> output should be:
>
> ['a', 'c', 'e', 'g']
>
> ['Orange', 'Strawberry', 'Peach']
>
> []
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list