# List¶

Ha Khanh Nguyen (hknguyen)

## 1. List¶

• Lists are variable-length and their contents can be modified in-place.
• You can define them using square brackets [] or using the list() type function:

## 2. Elements of a List¶

### 2.1 List indexing & slicing¶

• Use square brackets [] to access an element at a specific position in a list.
• Just like with strings, use [start:end] to get a "slice" of the list:

### 2.2 Modifying a list element¶

• To replace a list element with another object:

• Elements can be appended to the end of a list using the append() method.
• Note that the append() function does NOT return anything. Its only task is to change the object (the list) it was applied on.
• Ugh! Now we need to re-establish our b_list object since I ruined it!
• We can also add a new element at a specific position in the list using the insert() function.

### 2.4 Removing elements¶

• To remove an element from the list, we can use the remove() method.
• remove() scans the list (from left to right) and remove the first element of such value.
• To not receive an error, we first check whether the element we want to remove is in the list or not using in or not in keywords.

• First, we can use the in or not in keywords (operators) to check if an element is in the list:

• Checking whether a list contains a value is a lot slower than doing so with dictionary (covered in the next lecture), as Python makes a linear scan across the values of the list, whereas it can check the others (based on hash tables) in constant time.

### 2.5 Concatenating and combining lists¶

• Add 2 lists together using +
• We can also do this using the extend() method.
• Using the extend() function is a less computing-expensive operation compares to concatenation so it's recommended when you're building a very large list by putting smaller lists together.

### 2.6 Sorting¶

• You can sort a list in-place (without creating a new object) by calling its sort() function:
• One of the optional arguments of sort() is key. It takes on a function that produces a value to use to sort the objects.

• For example, we might want to sort our list of strings by their lengths:

• key can take on built-in functions like len(), but it can also take on user-defined functions.

This lecture note is modified from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.