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

Published: August 07, 2021

Tags: Python; List; Slicing;

DMCA.com Protection Status

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