Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One-Liners – The Ultimate Collection
1
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)
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: