Lists

Lists are mutable sequences that can store any data type, denoted by []. Elements are separated by commas and indexed 0-based. After creation, lists support indexing, slicing, adding/deleting elements, and sorting.

Creating Lists

Use [] or the list() function to create lists:

Empty list:

code.python
>>> a = []

List with elements:

code.python
>>> a = [1, 2, 3, 4, 5]
>>> a
[1, 2, 3, 4, 5]

List with mixed data types:

code.python
>>> a = [1, 5, 'b', False]
>>> a
[1, 5, 'b', False]

Convert iterable objects (strings, ranges, tuples, etc.) to lists with list():

code.python
>>> rg = range(8)
>>> a = list(rg)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7]

Adding Elements

Append: Add an element to the end with append() (fast):

code.python
>>> a = [1, 2, 3, 4]
>>> a.append(5)
>>> a
[1, 2, 3, 4, 5]

Extend: Add multiple elements from another sequence to the end with extend():

code.python
>>> a = [1, 2]
>>> a.extend([3, 4])
>>> a
[1, 2, 3, 4]

Insert: Insert an element at a specific position with insert(index, element):

code.python
>>> a = [1, 2, 4]
>>> a.insert(2, 3)  # Insert 3 at index 2
>>> a
[1, 2, 3, 4]

Concatenate: Use + to combine two lists into a new list:

code.python
>>> a = [1, 2] + [3, 4]
>>> a
[1, 2, 3, 4]

Indexing and Slicing

Indexing extracts a single element (0-based left-to-right, -1-based right-to-left):

code.python
>>> ls = ['a', 'b', 'c']
>>> ls[2]   # 3rd element(0-based)
'c'
>>> ls[-2]  # 2nd-last element(-1-based)
'b'

Slicing extracts a sublist (follows "left-closed, right-open").

Table 2-4 List Slicing Operations