![]() |
|
[Tut] How to Get a List Slice with Arbitrary Indices in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Get a List Slice with Arbitrary Indices in Python? (/thread-95762.html) |
[Tut] How to Get a List Slice with Arbitrary Indices in Python? - xSicKxBot - 06-18-2020 How to Get a List Slice with Arbitrary Indices in Python? To extract elements with specific indices from a Python list, use slicing Code: list[start:stop:step]Code: [lst[i] for i in indices]Code: indicesPeople 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: Problem: How to extract elements with specific indices from a Python list? Example: You’ve got the following elements. Code: lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']You want to create a new list of elements with Code: indices = [0, 2, 6]Code: ['a', 'c', 'g']![]() You can get a quick overview of the most Pythonic methods in our interactive Python shell: https://repl.it/@finxter/accesslistelements?lite=true Exercise: Run the code shell. Now, try to access the element with index 7 as well in each of the given methods! Method 1: List Comprehension A simple, readable, and efficient way is to use list comprehension that’s a compact way of creating lists. The simple formula is Code: [expression + context]
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: Code: 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']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: Method 2: NumPy Array Indexing 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: Code: import numpy as np
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a = np.array(lst)
indices = [0, 2, 6] out = a[indices]The output is: Code: print(out)
# ['a' 'c' 'g']You see that NumPy indexing is far more powerful than Python indexing—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 readability and conciseness. Related resources:
Method 3: Itemgetter The following method can be seen sometimes—using the Code: itemgetterCode: operatorCode: 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']The code performs the following steps:
Method 4: Manual Indices 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: Code: lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
out = [lst[0], lst[2], lst[6]]
print(out)
# ['a', 'c', 'g']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. Method 5: Simple Loop Here’s another approach that’s often used by coders who come from other programming languages such as Java or C++: using simple loops. Code: 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']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. ![]() Nothing wrong with that—don’t get me wrong! But if you want to increase your level of sophistication in Python, join my free email academy with many Python email courses that will sharpen your skills! Have I already said that it’s free? Join Python Email Academy! Where to Go From Here? Enough theory, let’s get some practice! 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? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? 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. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |