Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing non-consecutive elements of a list or string in python

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.

like image 407
beroe Avatar asked Oct 02 '13 01:10

beroe


People also ask

How do you check if an element is not there in a list?

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 .

How do you print a list of elements in Python?

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.


2 Answers

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) 
like image 104
John Y Avatar answered Sep 20 '22 13:09

John Y


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.

like image 25
justhalf Avatar answered Sep 19 '22 13:09

justhalf