How to get every nth element in a list in python ?

August 07, 2021    /    Viewed: 316    /    Comments: 0    /    Edit


Examples of how to get every nth element in a list in python:

Create a list in python

Lets first create a list in python

mylist = ['a','b','c','d','e','f','g','h','i']

To get an element stored in a list using its indexe:

mylist[0]

returns

'a'

and

mylist[4]

returns

'e'

Get every nth element in a list

To get every nth element in a list, a solution is to do mylist[::n].

To get for example every 2 elements in a list:

mylist[::2]

returns

['a', 'c', 'e', 'g', 'i']

Another example

mylist[::3]

returns

['a', 'd', 'g']

Get every nth element in a list, between indexes m1,m2

To get every nth element in list, between indexes m1,m2, a solution is to do mylist[m1:m2:n]. Example:

mylist[0:4:2]

returns

['a', 'c']

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!