Quick Article Summary to get a specific element from a list:
- Get elements by index
- use the operator
[]
with the element’s index - use the list’s method
pop(index)
- use slicing
lst[start:stop:step]
to get several elements at once - use the function
itemgetter()
from the operator module
- use the operator
- Get elements by condition
- use the
filter()
function - use a list comprehension statement
- use the
Python lists surely belong to the must-knows for any Python developer. They allow you to store, iterate and manipulate data effectively and with very little code. Yet, there is another important list topic: How to access list items?
In the first part of this article you will learn all possible ways how to get specific elements from a list. In the second part you will see how to apply the theory to practical questions.
Let’s take as example a list ps containing points from the 2D space. If you need more background on lists, I want to recommend you this article.
Get Specific Elements from List by Index
To access any item in a list use the brackets operator with the index of the item you want to retrieve. E.g. if we want to access the point (4, 5) from our list ps
we write:
# list of points from the 2D space ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] point = ps[2]
The indices start at 0, therefore the third element’s index is 2. In Python it is also possible to count from back to front using negative indices.
This is very handy, especially for retrieving the last or second last element.
The index of a list’s last element is -1, the index of the second last is -2 and so on.
Try it out:
Get Specific Elements from List using pop()
If you want to access and remove an item from a list, call the pop() method with
the index of the element. If you don’t pass a value for the index, the pop() method
returns and removes the last element from the list.
This is how you get and remove the item (4, 5) using the pop() method:
# list of points from the 2D space ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] item = ps.pop(2) print(ps) # [(2, 4), (-1, 7), (3, -4), (-1, -5)]
Now, the variable item has the value (4, 5).
Get Specific Elements from List with Slicing
To get a continuous range of elements from a list, use slicing.
Slicing also uses the brackets operator with a start and end index.
As code it looks as follows:
ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] items = ps[2:4]
where the first number before the colon (:) is the start index and the second number,
after the colon, is the end index. The start index is included, the end index is excluded.
In our example items = ps[2:4]
the start index is 2, the end index is 4.
Since the start index is included, we get the elements at indices 2 and 3.
The end index is not included, therefore the element at index 4 is not included.
Thus, the value of the variable items
will be [(4, 5), (3, -4)]
With slicing you can use a third parameter step to get items in a range with
regular distances. Read more about slicing in our detailed article.
itemgetter()
The module operator provides the itemgetter function which allows you
to access multiple elements from a list simultaniously.
Here is the code:
from operator import itemgetter ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] got = itemgetter(0, 2, 3)(ps)
After this line the variable got contains the items from the indices 0, 2, 3 as tuple.
Get Elements from List using filter()
In the solutions we discussed previously, we used indices to get elements from a
list. Another possibility is to get elements from a list by a certain condition.
For example, we could want to get all elements from the list ps that have a distance
of 6.0 or more from (0, 0). Since we don’t know the indices of those elements, we
can’t use a solution that requires the indices. Python provides a built-in function called filter().
The filter() method requires two parameters:
a function wich returns True/False and an iterable.
The filter() function applies the function to each element from the iterable and
keeps only the elements for which the function returned True.
Using the filter() function we can get all elements with a distance greater than
6.0 from (0, 0) like this:
def dist(x): return (x[0] ** 2 + x[1] ** 2) ** 0.5 ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] filtered = list(filter(lambda x: dist(x) > 6.0, ps))
As you can see in the code, the result of the filter() function has to be converted
back to a list.
List Comprehension with Condition
Need background on list comprehension? Read more here.
Another way to get all elements from a list which satisfy a certain condition is a
list comprehension. The algorithm behind the list comprehension is called Linear Search.
Linear Search iterates over the input once and appends all elements that satisfy the
condition to a new list.
In our example where we wanted to get all points from the list ps whose distance from
(0, 0) is larger than 6.0 we need the following code:
def dist(x): return (x[0] ** 2 + x[1] ** 2) ** 0.5 ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] filtered = [p for p in ps if dist(p) > 6.0]
Try it yourself:
Applications
In this section we want to widen the scope a bit and see how we can apply the
solutions presented above. Therefore we chose some common problems.
Get Specific Indices from List
To get all the indices of a subset of items which satisfy a certain condition,
use a list comprehenion:
def dist(x): return (x[0] ** 2 + x[1] ** 2) ** 0.5 ps = [(2, 4), (-1, 7), (4, 5), (3, -4), (-1, -5)] filtered = [idx for idx, p in enumerate(ps) if dist(p) > 6.0]
Get Specific Lines from File
Suppose you want to get all comments from a code file.
Again, I suggest to use a list comprehension and for analyzing each line a regular expression.
import re pattern = r'^#.*$' comments = [line for line in open('code.py') if re.match(pattern, line)]
If you want to know more about reading lines from a file, this article might be for you.
Get Specific Part of String
To get a specific part of a string or substring, use slicing.
For example, get the substring from 3 to 9 from the string ‘Python is cool!’.
s = 'Python is cool!' substring = s[3:10]
Get Specific Keys from Dict
Even though this topic might be more in the scope of dictionaries, I’d like to mention
that by converting a dictionary to a list, you get a list of the dictionary’s keys.
And now, we are back to the topic of getting specific elements from a list.
For more advanced problems, use the dicionary method items(). For example to retrieve all
keys whose value is a vowel:
d = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e'} vowels = [key for key, item in d.items() if item in 'aeiou']
Learn everything about Python dictionaries here!
Conclusion
If you want to get specific items from a list in Python you have several possibilities to do so.
You can group these solutions into two groups:
- Get elements by index
- use the operator [] with the element’s index
- use the list’s method pop(index)
- use slicing (lst[start:stop:step]) to get several elements at once
- use the function itemgetter() from the operator module
- Get elements by condition
- use the filter() function
- use a list comprehension
In any case it is important for any proficient Python programmer to master those
different solutions.