Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of R list()

Tags:

python-3.x

r

R's list() allow labelled elements as well, is there an equivalent way in Python to achieve the following?

list("prob", "topTalent", name="Roger")
like image 626
tejzpr Avatar asked Jun 07 '18 00:06

tejzpr


2 Answers

The Python documentation at https://docs.python.org/3/tutorial/introduction.html implies that you can create recursive structures (the proper R term for structures that can have a tree-characteristic) of varying types with the "[" operator:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]

I'm just an R guy but that would seem to imply that Python's "list" data-type strongly resembles R's list type.

To get named "recursive" structures, it appears one needs to use a "dictionary" ( created with flanking "{","}" ).

>>> x = {'a':a, 'n':n}
>>> x
{'a': ['a', 'b', 'c'], 'n': [1, 2, 3]}

It appears that Python requires names for its dictionary entries while R allows both named and unnamed entries in a list.

>>> x = {'a':a, 'n':n, 'z':[1,2,3], 'zz':{'s':[4,5,6], 'd':['t','y']} }
>>> x
{'a': ['a', 'b', 'c'], 'n': [1, 2, 3], 'z': [1, 2, 3], 'zz': {'s': [4, 5, 6], 'd': ['t', 'y']}}

The accession from Python dicts resembles the access to items when using R:

>>> x['zz']
{'s': [4, 5, 6], 'd': ['t', 'y']}
>>> x['zz']['s']
[4, 5, 6] 
like image 149
IRTFM Avatar answered Oct 11 '22 11:10

IRTFM


There's no equivalent. Python lists have nothing like R's names, and OrderedDict (as suggested in the comments) does not allow the equivalent of unnamed elements or duplicate names, as well as not supporting access by element position.

A dict would be the most common way of associating objects with names in Python, but it's still very different from an R list with names. You could certainly create your own class attempting to mimic the equivalent R data structure, perhaps subclassing list or collections.UserList, but you'd have to implement a lot of functionality yourself, and existing functions you pass your object to wouldn't know what to do with the names.

like image 21
user2357112 supports Monica Avatar answered Oct 11 '22 10:10

user2357112 supports Monica