Lists are a collection of datatypes that have an order.
The order is given by what is known as an index, where the count starts from 0 (First element is at index 0).
Here are how to initialize a list, using square brackets []
Creating Lists of Variable Length
List comprehension is a powerful tool in creating lists of variable length.
You will do this with a for loop inside []
Indexing and Slicing
Indexing and Slicing in lists is similar to strings.
Indexing is when you access one element of the list. Slicing is when you access a range of elements between a start and end index.
One special property of lists is that it is mutable. Note that in the String chapter we said that strings are immutable, meaning that you can index and
read from the string but you cannot change the character at the index directly. In Lists you are able to change the element at the index directly.
Operations
Here are some of the most common operations on a list, which are len(), max(), min() and sum()
Basic Operation
Finding Operation
These operation allow you to check for where an element is in a list or not. The two main operations are in and not in
Adding Operation
These operations allow you to add to a list, which also allows you to build variable length list
But first, lets discuss the difference between destructive and non-destructive operations. Destructive operations on a list change
the original list while non-destructive operations create a new copy of the list while doing the operation (this means the original list stays the same).
For example, assigning a value like a[0] = "hello" is destructive because it changes a. We will see further examples below.
This first operation is called .append(), which adds an element to the end of the list destructively
These two operations (.extend() and +=) are similar and both extends a list with another list destructively. Note that extending a singleton would have the same effect as append
Note how the above two operations are destructive as they change the original list a. Now I will introduce a non-destructive version of extend/+=
Deleting Operations
Here are the destructive deletion operations .remove() and .pop(). The .remove() method takes in an element and removes the first occurance of the element in the list. The .pop() method takes in an index and delete the element at that index in the list.
.remove() doesn't have a return value, but .pop() returns the value it popped
Get in touch
Contact us with questions through wechat or emails!