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



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Converting List of Strings to * [Ultimate Guide] xSicKxBot 0 643 05-02-2023, 01:17 PM
Last Post: xSicKxBot
  [Tut] Python f-Strings — The Ultimate Guide xSicKxBot 0 722 04-10-2023, 07:38 AM
Last Post: xSicKxBot
  [Tut] Ten Python One-Liners to Get Today’s Date as YYYY-MM-DD xSicKxBot 0 621 12-29-2022, 09:17 AM
Last Post: xSicKxBot
  [Tut] Python Find in List [Ultimate Guide] xSicKxBot 0 696 12-09-2022, 11:35 PM
Last Post: xSicKxBot
  [Tut] The Ultimate Guide on Converting a CSV in Python xSicKxBot 0 574 07-25-2022, 09:17 AM
Last Post: xSicKxBot
  [Tut] Python Unpacking [Ultimate Guide] xSicKxBot 0 626 06-06-2022, 01:03 AM
Last Post: xSicKxBot
  [Tut] The Ultimate Guide to Data Cleaning in Python and Pandas xSicKxBot 0 714 05-24-2022, 07:11 PM
Last Post: xSicKxBot
  [Tut] Python Join List [Ultimate Guide] xSicKxBot 0 929 06-06-2020, 05:22 PM
Last Post: xSicKxBot
  [Tut] Python Math Module [Ultimate Guide] xSicKxBot 0 829 06-03-2020, 11:36 PM
Last Post: xSicKxBot
  [Tut] Python Join List [Ultimate Guide] xSicKxBot 0 806 06-01-2020, 09:43 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016