03-28-2020, 02:37 PM
Python One-Liners – The Ultimate Collection
This resource is meant to be the ultimate collection of Python One-Liners. If you have an idea for a one-liner to be published here, send me a message at chris (at) finxter.com.
Find All Indices of an Element in a List
Say, you want to do the same as the list.index(element) method but return all indices of the element in the list rather than only a single one.
In this one-liner, you’re looking for element in the list so it even works if the element is not in the list (unlike the method).
This resource is meant to be the ultimate collection of Python One-Liners. If you have an idea for a one-liner to be published here, send me a message at chris (at) finxter.com.
Find All Indices of an Element in a List
Say, you want to do the same as the list.index(element) method but return all indices of the element in the list rather than only a single one.
In this one-liner, you’re looking for element
Code:
'Alice'Code:
[1, 2, 3]Code:
list.index()Code:
lst = [1, 2, 3]
indices = [i for i in range(len(lst)) if lst[i]=='Alice']
index = indices[0] if indices else None
print(index)
