1. Lists
In this lesson, you are going to learn how to use another data structure, Python's lists.
2. What is a list?
Lists are a very useful data structure for storing data. Unlike NumPy arrays, they are part of the Python Standard Library.
Lists can store a sequence of anything. Not just floats and integers, but they can even contain strings, other lists, NumPy arrays, and even functions. Any Python object can be stored in a list.
Unlike MATLAB cell arrays and NumPy arrays, lists are single-dimensional.
However, indexing into lists uses the same syntax that you've learned for indexing into NumPy arrays.
3. Making lists
Creating lists uses a similar syntax as creating matrices in MATLAB. We use square brackets to designate the start and end of the list, then separate the elements of the list with commas.
Here, I've created a list called my_list that contains a sequence of numbers. I can use the square brackets to index into the list and get the third item in the list using the index "2".
Similarly, I can get a range of values, just like we get ranges from NumPy arrays. Here, we are selecting the third item from the end through the end.
4. Making NumPy arrays from lists
While lists can be useful for simple tasks, they don't support the advanced features of NumPy like element-wise math.
But no fear! If you have a list and you want to do NumPy things, you can easily convert it to a NumPy array by passing it into NumPy's array() function.
5. Multidimensional NumPy arrays from lists of lists
Since lists can contain anything, they can even contain other lists. Here we have a list with three items, where each item is a list with two items: integers.
When we pass this list into NumPy's array() function, it returns a two-dimensional array with three rows and two columns.
6. Differences between lists and NumPy arrays
When working with lists and NumPy arrays, there are some important differences to keep in mind.
First, for NumPy arrays, all elements must be the same type, however, with lists you can mix types.
Second, operators may work differently between the two. For example, the plus operator does element-wise addition for NumPy arrays, while it performs concatenation on lists.
Third, NumPy arrays are multidimensional while lists have only a single dimension.
Finally, lists cannot be indexed with boolean arrays.
7. When to use each
These differences can make it hard to decide which to use, so here are some tips.
If you are doing math, you probably want to use a NumPy array.
If you are storing non-numerical structures, use lists.
If you have multidimensional data, use NumPy arrays.
8. Let's practice!
Now that you know what lists are used for let's practice.