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:
>>> a = []
List with elements:
>>> a = [1, 2, 3, 4, 5]
>>> a
[1, 2, 3, 4, 5]
List with mixed data types:
>>> a = [1, 5, 'b', False]
>>> a
[1, 5, 'b', False]
Convert iterable objects (strings, ranges, tuples, etc.) to lists with list():
>>> 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):
>>> 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():
>>> a = [1, 2]
>>> a.extend([3, 4])
>>> a
[1, 2, 3, 4]
Insert: Insert an element at a specific position with insert(index, element):
>>> 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:
>>> 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):
>>> 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