%% Use Python list Variables in MATLAB
% This example shows how to use Python® list variables in MATLAB®.
% To call a Python function that takes a list input argument, create a py.list variable. To convert a list to a MATLAB variable, call the cell function, then call the appropriate conversion function for each element in the list.
%% Call Python Function That Takes list Input Arguments
% The Python len function returns the number of items in a container, which includes a list object.

py.help('len')

% Call os.listdir to create a Python list of programs named P.

P = py.os.listdir("C:\Program Files\MATLAB");
class(P)

% Display the number of programs.

py.len(P)

% Display one element.

P{2}

%
%% Index into Python List
% Use MATLAB indexing to display elements in a list. For example, display the last element in the list. MATLAB returns a Python list.

P(end)

% You also can iterate over the list in a for loop.

for n = P
    disp(n{1})
end

%
%% Convert Python list Type to MATLAB Types
% This code displays the names in list P using MATLAB variables. Call cell to convert the list. The list is made up of Python strings, so call the char function to convert the elements of the cell array.

cP = cell(P);

% Each cell element name is a Python string.

class(cP{1})

% Convert the Python strings to MATLAB data.

mlP = string(cell(P));

% Display the names.

for n = 1:numel(cP)
    disp(mlP{n})
end

%
%% Use Python List of Numeric Types in MATLAB
% A Python list contains elements of any type and can contain elements of mixed types. The MATLAB double function used in this code assumes that all elements of the Python list are numeric.
% Suppose that you have a Python function that returns a list of integers P. To run this code, create the variable with these values.

P = py.list({int32(1), int32(2), int32(3), int32(4)})

% Display the numeric type of the values.

class(P{1})

% Convert P to a MATLAB cell array.

cP = cell(P);

% Convert the cell array to a MATLAB array of double.

A = cellfun(@double,cP)

%
%% Read Element of Nested list Type
% This code accesses an element of a Python list variable containing list elements. Suppose that you have this list.

matrix = py.list({{1, 2, 3, 4},{'hello','world'},{9, 10}});

% Display element 'world', which is at index (2,2).

disp(char(matrix{2}{2}))

%
%% Display Stepped Range of Python Elements
% If you use slicing to access elements of a Python object, the format in Python is start:stop:step. In MATLAB, the syntax is of the form start:step:stop.

li = py.list({'a','bc',1,2,'def'});
li(1:2:end)

% Copyright 2021-2021 The MathWorks, Inc.