I have the general idea of how to do this in php, but I am new to Python and not sure how to do it.
I am trying to implement a function that returns a list
containing every second element of every three elements of the list.
For example, if my list is:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12]
I would like the function to return:
[2,5,8,11]
In General I am thinking we will slice the total values of the list in 3 equal parts then get every second element?
[1, 2, 3,| 4, 5, 6,| 7, 8, 9,| 10,11,12] => [2,5,8,11]
I have tried python split function but it doesn't work on list. I would also has to be consider total length of the list. It might be an even number.
All you need is list slicing starting from index 1
and then you need to jump by 3
indexes:
>>> my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> my_list[1::3]
[2, 5, 8, 11]
General syntax of list slicing is your_list[start:end:jump]
where:
start
: is the starting index for slicing the list. Empty value means start of the list i.e. index 0
end
: is the index till which you want to slice the list. Empty value means end of the list
jump
: is used to jump the elements from start
such that you'll get values in the order start
, start+jump
, start+2*jump
, so on till your list reaches end
. Empty value means 1
As mentioned by Mr. cᴏʟᴅsᴘᴇᴇᴅ in comment, for large lists one should prefer itertools.islice
which returns iterator object and could be used in this case as:
from itertools import islice # import islice
islice(my_list, 1, None, 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With