Python: List
Syntax of list
literal expression for list:
[x0, x1, x2, etc]
- Items can be any type.
- Items need not be all the same type.
- Items can be added, or removed. (the list can grow or shrink. Not fixed length)
- Access to any item is constant time.
- Python list is implemented as dynamic array.
x = [1, 2, "m"] print(x) # [1, 2, 'm']
0-based index
List index start at 0. Best to think of it as between items.
x = ["a", "b", "c", "d"] # 0 1 2 3 ← index boundaries
Negative index counts from right.
Total number of items
len(list)-
Return the count of number of items.
x = [0, 1, 2] print(len(x)) # 3
Check exist
x in list-
check if exist.
print(2 in [0, 1, 2]) # True print(9 in [0, 1, 2]) # False x not in list-
return true if not in list.
print(3 not in [0, 1, 2]) # True
Get one item
list[i]-
Return item at index i.
x = ["a", "b", "c"] print(x[1]) # b x = ["a", "b", "c"] print(x[-1]) # c
Set or change one item
list[i] = newValue-
Change a item's value.
x = [1, 2, 3] x[2] = "b" print(x) # [1, 2, 'b']
Delete one item
del list[i]-
Delete item at index i.
x = ["a", "b", "c"] del x[1] print(x) # ['a', 'c']
Get a slice
list[i:j]-
Return a slice from index i to j.
x = [0, 1, 2, 3, 4, 5] print(x[1:4]) # [1, 2, 3] list[i:j:k]-
every kth.
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(x[1:10:2]) # [1, 3, 5, 7, 9] list[:j]-
From beginning to j.
list[i:]-
From i to the end.
x = [0, 1, 2, 3, 4, 5] print(x[3:]) # [3, 4, 5]
Delete a slice
del list[i:j]-
delete the items between i to j.
🛑 WARNING:
delis a statement, not a function. It cannot be used as expression in function argument.xx = [1, 2, 3, 4, 5] del xx[1:3] print(xx) # [1, 4, 5] del list[i:j:k]-
delete every kth item between i to j.
Replace a slice
list[i:j] = list2-
Replace i to j items by the content of list2
x = [1, 2, 3, 4, 5] x[2:4] = [99, 100] print(x) # [1, 2, 99, 100, 5] list[i:j:k] = list2-
Replace items
list[i:j:k]by content of list2. (list2 must have same number of items)# list slice alternate assignment example xx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] xx[0:10:2] = ["a", "a", "a", "a", "a"] print(xx) # ['a', 2, 'a', 4, 'a', 6, 'a', 8, 'a', 10, 11, 12]
Nested lists
Lists can be nested arbitrarily. Example:
x = [3, 4, [7, 8]]
Append extra bracket to get item of nested list.
x = [3, 4, [7, 8]] print(x[2][1]) # 8
Join lists
list1 + list2-
Join two lists into one.
see also
append. Python: List Methodsx = [1, 2] + [7, 6] print(x) # [1, 2, 7, 6]
Python, Data Structure
- Python: List
- Python: Generate List: range
- Python: List Comprehension
- Python: List Methods
- Python: Iterate List
- Python: Map f to List
- Python: Filter List
- Python: Iterator to List
- Python: Copy Nested List, Shallow Copy vs Deep Copy
- Python: Interweave Lists to Tuples, Transpose
- Python: Sort
- Python: Convert List to Dictionary