Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Get a List Slice with Arbitrary Indices in Python?

#1
How to Get a List Slice with Arbitrary Indices in Python?

<div><p class="has-background has-luminous-vivid-amber-background-color"><strong>To extract elements with specific indices from a Python list, use slicing <code>list[startConfusedtopConfusedtep]</code>. If you cannot use slicing because there’s no pattern in the indices you want to access, use the list comprehension statement <code>[lst[i] for i in indices]</code>, assuming your indices are stored in the variable <code>indices</code>.</strong></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="How to Get a List Slice with Arbitrary Indices in Python?" width="1400" height="788" src="https://www.youtube.com/embed/8kMVqhGgIHE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>People always want to know the most Pythonic solution to a given problem. This tutorial shows you the most Pythonic solution(s) to the following problem:</p>
<p><strong>Problem</strong>: How to extract elements with specific indices from a Python list?</p>
<p><strong>Example</strong>: You’ve got the following elements.</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 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']</pre>
<p>You want to create a new list of elements with <code>indices = [0, 2, 6]</code> in the original list:</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="">['a', 'c', 'g']</pre>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/getspecific-1024x576.jpg" alt="How to get elements with specific indices from a Python list?" class="wp-image-9753" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/getspecific-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p>You can get a quick overview of the most Pythonic methods in our interactive Python shell:</p>
<p> <iframe src="https://repl.it/@finxter/accesslistelements?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="1500px" frameborder="no"></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code shell. Now, try to access the element with index 7 as well in each of the given methods!</em></p>
<h2>Method 1: List Comprehension</h2>
<p>A simple, readable, and efficient way is to use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> that’s a compact way of creating <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener">lists</a>. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression</strong>: What to do with each list element?</li>
<li><strong>Context</strong>: What elements to select? The context consists of an arbitrary number of <code>for</code> and <code>if</code> statements.</li>
</ul>
<p>Here’s the code that creates a new list that contains the elements at specific indices (e.g., 0, 2, and 6) in the original list:</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 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = [lst[i] for i in indices]
print(out)
# ['a', 'c', 'g']</pre>
<p>In most cases, this will be the best solution because you don’t need any library and it’s still short and readable. However, if you need to do this multiple times, it may be better to import the NumPy library:</p>
<h2>Method 2: NumPy Array Indexing</h2>
<p>Python’s library for numerical computations, NumPy, is one of the most powerful tools in your toolbelt—especially if you work as a data scientist. Here’s how you can use NumPy to access arbitrary indices, given a sequence of specific indices:</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="">import numpy as np
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a = np.array(lst)
indices = [0, 2, 6] out = a[indices]</pre>
<p>The output is:</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="">print(out)
# ['a' 'c' 'g']</pre>
<p>You see that <a href="https://blog.finxter.com/how-to-use-numpy-boolean-indexing-to-uncover-instagram-influencers/" target="_blank" rel="noreferrer noopener">NumPy indexing</a> is far more powerful than <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" target="_blank" rel="noreferrer noopener">Python indexing</a>—it allows you to use arbitrary sequences as indices. Especially, if you need to do multiple of those numerical operations, you may want to import the NumPy library once and gain much in <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">readability and conciseness</a>.</p>
<p><strong>Related resources:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener">Dive into NumPy in our detailed blog tutorial. </a></li>
<li><a href="https://blog.finxter.com/coffee-break-numpy/" target="_blank" rel="noreferrer noopener">Become a Data Science Master by reading our book “Coffee Break NumPy”. </a></li>
</ul>
<h2>Method 3: Itemgetter</h2>
<p>The following method can be seen sometimes—using the <code>itemgetter</code> function from the <code>operator</code> module:</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="">from operator import itemgetter
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = list(itemgetter(*indices)(lst))
print(out)
# ['a', 'c', 'g']</pre>
<p>The code performs the following steps:</p>
<ul>
<li>Call the <code>itemgetter()</code> function and pass the arguments 0, 2, and 6. We use the asterisk operator <code>*</code> to unpack the values from the <code>indices</code> variable into the <code>itemgetter()</code> function. <a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank">Learn more about the asterisk operator in our detailed blog article.</a></li>
<li>This returns a new itemgetter function object. </li>
<li>Call the new itemgetter function object by passing the original list <code>lst</code>. </li>
<li>The new itemgetter function will now get a tuple of the items at positions 0, 2, and 6 in the original list lst. </li>
<li>Convert the tuple to a list using the <code>list(...</code>) built-in Python function.</li>
</ul>
<h2>Method 4: Manual Indices</h2>
<p>Just for comprehensibility, I also want to point out the “naive” way of accessing a few elements in the original list and put them into a new list:</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 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
out = [lst[0], lst[2], lst[6]]
print(out)
# ['a', 'c', 'g']</pre>
<p>This is a perfectly valid and efficient approach if you have only a few elements to access. For more than, say, five indices, it quickly becomes unhandy though.</p>
<h2>Method 5: Simple Loop</h2>
<p>Here’s another approach that’s often used by coders who come from other programming languages such as Java or C++: using simple loops. </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 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = []
for i in indices: out.append(lst[i])
print(out)
# ['a', 'c', 'g']
</pre>
<p>While there’s nothing wrong with this, it looks somehow “brutal” to an advanced coder. If you’d use this method, it would be like shouting into the world that you’re not a very sophisticated Python coder. <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Nothing wrong with that—don’t get me wrong! But if you want to increase your level of sophistication in Python, <a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">join my free email academy</a> with many Python email courses that will sharpen your skills! Have I already said that it’s free?</p>
<p><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank"><strong>Join Python Email Academy!</strong></a></p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/06/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016