All Indexes of Value

PythonPythonBeginner
Practice Now

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

Introduction

In Python, a list is a collection of items that are ordered and changeable. Sometimes, we need to find all the indexes of a specific value in a list. In this challenge, you will create a function that returns a list of indexes of all the occurrences of an element in a list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13658{{"`All Indexes of Value`"}} python/conditional_statements -.-> lab-13658{{"`All Indexes of Value`"}} python/for_loops -.-> lab-13658{{"`All Indexes of Value`"}} python/list_comprehensions -.-> lab-13658{{"`All Indexes of Value`"}} python/lists -.-> lab-13658{{"`All Indexes of Value`"}} python/tuples -.-> lab-13658{{"`All Indexes of Value`"}} python/function_definition -.-> lab-13658{{"`All Indexes of Value`"}} python/build_in_functions -.-> lab-13658{{"`All Indexes of Value`"}} end

All Indexes of Value

Write a Python function called index_of_all(lst, value) that takes a list lst and a value value as arguments and returns a list of indexes of all the occurrences of value in lst.

To solve this problem, you can use enumerate() and a list comprehension to check each element for equality with value and adding i to the result.

def index_of_all(lst, value):
  return [i for i, x in enumerate(lst) if x == value]
index_of_all([1, 2, 1, 4, 5, 1], 1) ## [0, 2, 5]
index_of_all([1, 2, 3, 4], 6) ## []

Summary

In this challenge, you learned how to find all the indexes of a specific value in a list using Python. You used enumerate() and a list comprehension to check each element for equality with value and adding i to the result. Keep practicing to improve your Python skills!

Other Python Tutorials you may like