Sick Gaming
[Tut] Python One-Liners – The Ultimate Collection - Printable Version

+- Sick Gaming (https://sickgaming.net)
+-- Forum: Programming (https://sickgaming.net/forum-76.html)
+--- Forum: Python (https://sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python One-Liners – The Ultimate Collection (/thread-94283.html)



[Tut] Python One-Liners – The Ultimate Collection - xSicKxBot - 03-28-2020

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
Code:
'Alice'
in the list
Code:
[1, 2, 3]
so it even works if the element is not in the list (unlike the
Code:
list.index()
method).

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)