Lists

Python for MATLAB Users

Justin Kiggins

Product Manager

What is a list?

  • Simple Python structure for storing data
  • Lists can hold anything
  • Similar to MATLAB's cell array
  • But only one-dimensional
  • Indexing like NumPy arrays
Python for MATLAB Users

Making lists

my_list = [8, 6, 7, 5, 3, 0 ,9]

print(my_list[2])
7
print(my_list[-3:])
[3, 0, 9]
Python for MATLAB Users

Making NumPy arrays from lists

my_list = [8, 6, 7, 5, 3, 0 ,9]
import numpy as np

my_array = np.array(my_list)
type(my_array)
numpy.ndarray
Python for MATLAB Users

Multidimensional NumPy arrays from lists of lists

list_of_lists = [[2, 3], [9, 0], [1, 4]]

import numpy as np arr = np.array(list_of_lists) print(arr)
[[2, 3]
 [9, 0]
 [1, 4]]
arr.shape
(3, 2)
Python for MATLAB Users

Differences between lists and NumPy arrays

NumPy Arrays Lists
All elements must be same type Can mix types
(+) does element-wise addition (+) concatenates lists
Multidimensional Single dimension
Range & Boolean indexing Only Range indexing
Python for MATLAB Users

When to use each

  • Need to do math?

    • NumPy array
  • Storing complex structures?

    • list
  • Multidimensional data?

    • NumPy array
Python for MATLAB Users

Let's practice!

Python for MATLAB Users

Preparing Video For Download...