03-28-2020, 02:37 PM
Python One-Liners – The Ultimate Collection
<div><p>This resource is meant to be the ultimate collection of <a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener">Python One-Liners</a>. If you have an idea for a one-liner to be published here, send me a message at chris (at) finxter.com. </p>
<h2>Find All Indices of an Element in a List</h2>
<p>Say, you want to do the same as the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-index/" target="_blank">list.index(element)</a> method but return all indices of the element in the list rather than only a single one. </p>
<p>In this one-liner, you’re looking for element <code>'Alice'</code> in the list <code>[1, 2, 3]</code> so it even works if the element is not in the list (unlike the <code>list.index()</code> method). </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre></p>
</div>
https://www.sickgaming.net/blog/2020/03/...ollection/
<div><p>This resource is meant to be the ultimate collection of <a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener">Python One-Liners</a>. If you have an idea for a one-liner to be published here, send me a message at chris (at) finxter.com. </p>
<h2>Find All Indices of an Element in a List</h2>
<p>Say, you want to do the same as the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-index/" target="_blank">list.index(element)</a> method but return all indices of the element in the list rather than only a single one. </p>
<p>In this one-liner, you’re looking for element <code>'Alice'</code> in the list <code>[1, 2, 3]</code> so it even works if the element is not in the list (unlike the <code>list.index()</code> method). </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre></p>
</div>
https://www.sickgaming.net/blog/2020/03/...ollection/