Create an account


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

<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/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016