Update snippets
This commit is contained in:
@ -5,7 +5,7 @@ tags: list,beginner
|
||||
|
||||
Checks if all elements in a list are equal.
|
||||
|
||||
- Use `set()` to eliminate duplicate elements and then use `len()` to check if length is 1.
|
||||
- Use `set()` to eliminate duplicate elements and then use `len()` to check if length is `1`.
|
||||
|
||||
```py
|
||||
def all_equal(lst):
|
||||
|
||||
18
snippets/index_of_all.md
Normal file
18
snippets/index_of_all.md
Normal file
@ -0,0 +1,18 @@
|
||||
---
|
||||
title: index_of_all
|
||||
tags: list,intermediate
|
||||
---
|
||||
|
||||
Returns a list of indices of all the occurrences of an element in a list.
|
||||
|
||||
- Use `enumerate()` and a list comprehension to check each element for equality with `value` and adding `i` to the result.
|
||||
|
||||
```py
|
||||
def index_of_all(lst, value):
|
||||
return [i for i, x in enumerate(lst) if x == value]
|
||||
```
|
||||
|
||||
```py
|
||||
index_of_all([1, 2, 1, 4, 5, 1], 1) # [0, 2, 5]
|
||||
index_of_all([1, 2, 3, 4], 6) # []
|
||||
```
|
||||
@ -1,19 +0,0 @@
|
||||
---
|
||||
title: indices_of_occurrence
|
||||
tags: list,beginner
|
||||
---
|
||||
|
||||
Returns a list of indices of all the occurrences of an element in a list.
|
||||
|
||||
- Use `enumerate()` to get index and value simultaneously while iterating.
|
||||
- Use `==` to check equality, if current element `val` is equal to `value`. Then `idx` to list.
|
||||
|
||||
```py
|
||||
def indices_of_occurrence(lst, value):
|
||||
return [idx for idx, val in enumerate(lst) if val == value]
|
||||
```
|
||||
|
||||
```py
|
||||
indices_of_occurrence([1, 2, 1, 4, 5, 1], 1) # [0, 2, 5]
|
||||
indices_of_occurrence([1, 2, 3, 4], 6) # []
|
||||
```
|
||||
Reference in New Issue
Block a user