Access Elements in Python Container Types
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 values: [2.0, 3.0] Use string, double or cell function to convert to a MATLAB array.
Use curly braces {}
to get the contents of the element.
res = li{1}
res = 1
Mapping Types
For mapping types, use curly braces with the Python key argument.
patient = py.dict(name="John Doe",billing=127); patient{"billing"}
ans = 127
Size and Dimensions
MATLAB displays information for your system.
p = py.sys.path; class(p)
ans = 'py.list'
Index into p
.
p(1) p{1}
ans = Python list with values: ['c:\\work'] Use string, double or cell function to convert to a MATLAB array. ans = Python str with no properties. c:\work
Inspect dimensions.
len = length(p) sz = size(p)
len = 11 sz = 1×2 1 11
Array Support
MATLAB converts a sequence type into a 1
-by-N
array.
Indexing
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
|
Logical indexing. |
Accessing data in a container with an arbitrary array of indices. An
index must be of the form |
Comma-separated lists. |
|
Related Examples
- Use Python str Variables in MATLAB
- Use Python list Variables in MATLAB
- Use Python tuple Variables in MATLAB
- Use Python Dictionaries in MATLAB