Main Content

Access Elements in Python Container Types

To work with a Python® variable in MATLAB®, convert the Python object to a MATLAB array, and then index into the array as needed. You also can preserve the Python object without converting, for example, to pass the object to a Python method.

A Python container is typically a sequence type (list or tuple) or a mapping type (dict). In Python, use square brackets [] or the operator.getitem function to access an element in the container. Scalar string arguments can be used to index into the container.

Sequence Types

Python sequence types behave like MATLAB cell arrays.

Get a subsequence using smooth-parenthesis () indexing.

li = py.list({1,2,3,4});
res = li(2:3)
res = 

  Python list with no properties.

    [2.0, 3.0]

Use curly braces {} to get the contents of the element.

res = li{1}
res =


Mapping Types

For mapping types, use curly braces with the Python key argument.

patient = py.dict(name="John Doe",billing=127);
ans =


Size and Dimensions

MATLAB displays information for your system.

p = py.sys.path;
ans =


Index into p.

ans = 

  Python list with no properties.


ans = 

  Python str with no properties.


Inspect dimensions.

len = length(p)
sz = size(p)
len =


sz =

     1    11

Array Support

MATLAB converts a sequence type into a 1-by-N array.


Python uses zero-based indexing; MATLAB uses one-based indexing. In Python programming, you access the elements of array x of length len using x(0) through x(len-1). When working with this array in MATLAB, you access these elements using x(1) through x(len).

Limitations to Indexing into Python Objects

You can access data in Python container objects, like lists and dictionaries, with index values, similar to referencing an element in a MATLAB matrix. There are, however, ways to index into matrices which are not supported for these Python types.

Indexing Features Not Supported in MATLAB

Use of square brackets, [].

Indexing into a container type that does not inherit from collections.Sequence or collections.Mapping.

Logical indexing.

Accessing data in a container with an arbitrary array of indices. An index must be of the form start:step:stop.

Comma-separated lists.

numel function does not return number of array elements. Returns 1.

Related Examples

More About