Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a list starting from given index and jumping/stepping it with some integer

Tags:

python

list

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.

like image 244
user9201290 Avatar asked Sep 05 '25 03:09

user9201290


1 Answers

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)
like image 69
Moinuddin Quadri Avatar answered Sep 07 '25 15:09

Moinuddin Quadri