Every nth element in list

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can access elements in a list using their index. Sometimes we may want to extract every nth element from a list. In this challenge, you are tasked with writing a function that takes a list and an integer nth as arguments and returns a new list containing every nth element of the original list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/comments -.-> lab-13626{{"Every nth element in list"}} python/lists -.-> lab-13626{{"Every nth element in list"}} python/tuples -.-> lab-13626{{"Every nth element in list"}} python/function_definition -.-> lab-13626{{"Every nth element in list"}} end

Every nth element in list

Write a function every_nth(lst, nth) that takes a list lst and an integer nth as arguments and returns a new list containing every nth element of the original list.

def every_nth(lst, nth):
  return lst[nth - 1::nth]
every_nth([1, 2, 3, 4, 5, 6], 2) ## [ 2, 4, 6 ]

Summary

In this challenge, you learned how to extract every nth element from a list in Python. You can achieve this by using slice notation to create a new list that contains every nth element of the given list.