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(pyargs('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.

Use Zero-Based Indexing for Python Functions

Python uses zero-based indexing; MATLAB uses one-based indexing. When you call a Python function, such as py.sys.path, the index value of the first element of a Python container, x, is int32(0). The index value for the last element is int32(py.len(x)-1).

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