As far as I can tell, this is not officially not possible, but is there a "trick" to access arbitrary non-sequential elements of a list by slicing?
For example:
>>> L = range(0,101,10) >>> L [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Now I want to be able to do
a,b = L[2,5]
so that a == 20
and b == 50
One way besides two statements would be something silly like:
a,b = L[2:6:3][:2]
But that doesn't scale at all to irregular intervals.
Maybe with list comprehension using the indices I want?
[L[x] for x in [2,5]]
I would love to know what is recommended for this common problem.
Use not in to Check if an Element Is Not in a List in Python. If we need to check if an element is not in the list, we can use the not in keyword. The not is a logical operator to converts True to False and vice-versa. So if an element is not present in a list, it will return True .
Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.
Probably the closest to what you are looking for is itemgetter
(or look here for Python 2 docs):
>>> L = list(range(0, 101, 10)) # works in Python 2 or 3 >>> L [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] >>> from operator import itemgetter >>> itemgetter(2, 5)(L) (20, 50)
If you can use numpy
, you can do just that:
>>> import numpy >>> the_list = numpy.array(range(0,101,10)) >>> the_indices = [2,5,7] >>> the_subset = the_list[the_indices] >>> print the_subset, type(the_subset) [20 50 70] <type 'numpy.ndarray'> >>> print list(the_subset) [20, 50, 70]
numpy.array
is very similar to list
, just that it supports more operation, such as mathematical operations and also arbitrary index selection like we see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With