Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Python Lists by index

Tags:

python

list

I am coming from an R background an trying to figure out a way to access a number of elements from a list given the index. A simple example is below:

my_list = ["a", "b", "c", "d", "e", "f", "g"]
my_elements = itemgetter(*[1,2])(list(my_list))
my_elements

This will return the first and second elements -- great! But I run into problems when I want to specify a sequence of integers to pull. The R implementation of what I would be doing would be:

my_list = c("a", "b", "c", "d", "e", "f", "g")
my_elements = my_list[c(1,3:5)]
my_elements

How would I do the equivalent in python? I have tried something like:

my_elements = itemgetter(*[1, list(range(3,6))])(list(my_list))

But I have to concert the range object and then it adds a list of numbers to the list rather the sequence of numbers directly. I am new to Python but I feel like there must be a very simple way of doing this I am overlooking?

like image 299
niccalis Avatar asked Jan 01 '23 10:01

niccalis


2 Answers

Note, it may be overkill, but if you are coming from R, you may consider the numpy/pandas libraries for the sort of functionality you would be used to, so, using a numpy.ndarray instead of a list object, you can use:

>>> import numpy as np
>>> arr = np.array(["a", "b", "c", "d", "e", "f", "g"])
>>> arr[np.r_[1, 3:6]]
array(['b', 'd', 'e', 'f'],
      dtype='<U1')

The indexing for numpy/pandas data structures will be more familiar to an R user. Python is not a domain-specific, statistical programming language, it is general purpose, so this sort of fancy-indexing isn't built-in.

like image 53
juanpa.arrivillaga Avatar answered Feb 02 '23 01:02

juanpa.arrivillaga


Examples of basic indexing and slicing:

my_list = ["a", "b", "c", "d", "e", "f", "g"]

print(my_list[1])  # indexing: get second item
print(my_list[:4:2]  # slicing: get every second item for items 1-4

# getting several items from different positions
my_list[1:2] + my_list[4:6]  # list concatenation

Actually, this explanation is very nice: Understanding slice notation

Examples of custom slicing:

from operator import itemgetter

itemgetter(2, 5, 3)(my_list)

lst_ids = [2,5,3]
getter = itemgetter(*lst_ids)
new_list = list(getter(my_list))
like image 22
sammy Avatar answered Feb 02 '23 02:02

sammy