Skip to main content
Practice

rotten-apples

---
id: rotten-apples
title: Finding Rotten Apples Explained
description: Write a Python function to find the positions of rotten apples in a given list
tags:
- Python
- List
- Function
sidebar_position: 2
isPublic: false
---

# Finding Rotten Apples Explained

The state of apples is given in a list, where rotten apples are represented as '0', and fresh apples as '1'.

The function takes this list as input and returns the `positions (indices) of rotten apples` in a `list format`.

<br />

```python title="Sample Solution"
def solution(apples):
return [index for index, apple in enumerate(apples) if apple == 0]
  • Using enumerate(apples), retrieve the index and value of each apple.

  • Filter out rotten apples with if apple == 0.

  • Use list comprehension to return all indices of rotten apples.


Usage Example

Input and Output Example
print(solution([1, 0, 1, 0, 1]))  # Output: [1, 3]

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.