# empty list print([]) # Output: [] print(list()) # Output: [] # default values print(['a', 'b', 'c']) # Output: ['a', 'b', 'c'] print(["a", "b", "c"]) # Output: ['a', 'b', 'c'] # mixed types print([['a', 'b'], ['c', 'd'], 1]) # Output: [['a', 'b'], ['c', 'd'], 1] # type/isinstance methods print(type([])) # Output: <class 'list'> print(isinstance([], list)) # Output: True
x = ['a', 'b', 'c'] print(x[0]) # Output: a print(x[1]) # Output: b print(x[-1]) # Output: c print(x[-2]) # Output: bIf the list is empty, using any index to access an item in the list will return an error.
y = [] # Raise IndexError: list index out of range #y[0] #y[1] #y[-1 z = ["a"] # Raise IndexError: list index out of range #z[1] #z[-2]
x = ['a', 'b', 'c'] x.append('d') print(x) # Output: ['a', 'b', 'c', 'd']
x.insert(0, 'x') print(x) # Output: ['x', 'a', 'b', 'c', 'd']
x.extend(['y', 'z']) print(x) # Output: ['x', 'a', 'b', 'c', 'd', 'y', 'z']
print(['a', 'b'] + ['c', 'd']) # Output: ['a', 'b', 'c', 'd']
x = ['a', 'b', 'c', 'd'] # you can modify an item from any position in the list x[0] = 'A' print(x) # Output: ['A', 'b', 'c', 'd']
x = ['a', 'b', 'c', 'd'] x[1:3] = ['B', 'C'] print(x) # Output: ['a', 'B', 'C', 'd']
x = ['a', 'b', 'c', 'd'] x[2:2] = ['X', 'Y'] print(x) # Output: ['a', 'b', 'X', 'Y', 'c', 'd']
x = ['a', 'b', 'c', 'd'] # you can remove an item from any position in the list del x[0] print(x) # Output: ['b', 'c', 'd']
x = ['a', 'b', 'c', 'd'] # you can remove an item from any position in the list del x[1:3] print(x) # Output: ['a', 'd']
x = ['a', 'b', 'c', 'd'] # the item removed can be assigned or printed if needed last = x.pop() print(last) # Output: d print(x) # Output: ['a', 'b', 'c']
x = ['a', 'b', 'c', 'd'] # the item removed can be assigned or printed if needed second = x.pop(1) print(second) # Output: b print(x) # Output: ['a', 'c', 'd']
x = ['a', 'b', 'c', 'c'] # the function remove deletes only the first occurrence of the value x.remove('c') print(x) # Output: ['a', 'b', 'c']
x = ['a', 'b', 'c', 'd'] x.clear() print(x) # Output: []
x = ['b', 'd', 'a', 'c'] x.sort() print(x) # Output: ['a', 'b', 'c', 'd'] x.sort(reverse=True) print(x) # Output: ['d', 'c', 'b', 'a']
x = ['b', 'd', 'a', 'c'] print(sorted(x)) # Output: ['a', 'b', 'c', 'd'] print(sorted(x, reverse=True)) # Output: ['d', 'c', 'b', 'a'] print(x) # Output: ['b', 'd', 'a', 'c']
# sort by length x = ['a', 'ab', 'abc', 'abcd'] x.sort(key=len, reverse=True) print(x) # Output: ['abcd', 'abc', 'ab', 'a'] # case-insensitive sorting x = ['Abcd', 'abC', 'aB', 'A'] x.sort(key=str.lower) print(x) # Output: ['A', 'aB', 'abC', 'Abcd'] # using lambda x = ['a', 'ab', 'abc', 'abcd'] x.sort(key=lambda i: len(i), reverse=True) print(x) # Output: ['abcd', 'abc', 'ab', 'a']
x = ['b', 'd', 'a', 'c'] x.reverse() print(x) # Output: ['c', 'a', 'd', 'b'] x.reverse() print(x) # Output: ['b', 'd', 'a', 'c']
x = ['b', 'd', 'a', 'c'] y = x[::-1] # new list created print(y) # Output: ['c', 'a', 'd', 'b'] print(x) # Output: ['b', 'd', 'a', 'c']
# index(ITEM) - returns first index of item x = ['a', 'a', 'b'] print(x.index('a')) # Output: 0 # index(ITEM, START_INDEX) - returns first index of item starting from START_INDEX print(x.index('a', 1)) # Output: 1 # index(ITEM, START_INDEX, END_INDEX) - returns first index of item between START_INDEX and END_INDEX print(x.index('a', 1, 2)) # Output: 1
print('A' in ['A', 'B']) # Output: True print('A' not in ['A', 'B']) # Output: False
x = ['b', 'd', 'a', 'c'] for y in x: print(y)Output:
b d a c
for x in range(1, 3): # in language C, this is similar to: for (int i=1, i < 3, i++) ... print(x)Output:
1 2
x = list(range(0, 4)) print(x) # Output: [0, 1, 2, 3] x = list(range(1, 4)) print(x) # Output: [1, 2, 3]
x = ["a", "b", "c"] for index, item in enumerate(x): print(f"{index}:{item}")Output:
0:a 1:b 2:c
x = ["a", "b", "c"] for index, item in enumerate(x, start=1): print(f"{index}:{item}")Output:
1:a 2:b 3:c
x = [1, 2] y = ["a", "b"] z = ["A", "B"] for i, j, k in zip(x, y, z): print(f"{i}:{j}:{k}")Output:
1:a:A 2:b:B
# traditional approach y = [] for x in range(1, 3): y.append(x ** 2) print(y) # Output: [1, 4] # list comprehension z = [(x ** 2) for x in range(1, 3)] print(z) # Output: [1, 4]
w = [(x ** 2) for x in range(1, 3) if x % 2 == 0] print(w) # Output: [4]
w = [1, -2] z = [x if x >=0 else -x for x in w] print(z) # Output: [1, 2]
w = ['a', 'b'] z = [x.upper() for x in w] print(z) # Output: ['A', 'B']
x = [[1, 2], [3, 4]] y = [row for row in x] print(y) # Output: [[1, 2], [3, 4]] flattened = [num for row in x for num in row] print(flattened) # Output: [1, 2, 3, 4]
x = [0, 1, 2, 3, 4, 5]You can specify the index of the first item (inclusive) and the last item (exclusive):
print(x[1:3]) # Output: [1, 2]You can skip the index of the first item (defaults to 0)
print(x[:4]) # Output: [0, 1, 2, 3]You can skip the index of the last item (defaults to the length of the list):
print(x[3:]) # Output: [3, 4, 5]You can skip the index of the first and last item (useful to copy a list): index of the first item default to 0 and the last defaults to the length of the list
print(x[:]) # Output: [0, 1, 2, 3, 4, 5]To get the slice of the last items, you can use a negative index:
print(x[-3:]) # Output: [3, 4, 5] print(x[:-3]) # Output: [0, 1, 2]You can decide how many items to skip between items in the specified range by setting a third index in the brackets:
print(x[0:6:2]) # Output: [0, 2, 4] # first:last:step=2 print(x[::2]) # Output: [0, 2, 4] # reverse slicing print(x[::-1]) # Output: [5, 4, 3, 2, 1, 0] print(x[::-2]) # Output: [5, 3, 1]
for y in x[0:6:2]: print(y)Output:
0 2 4
x = [1, 2, [3, 4]]Copy by reference:
y = x # both x and y reference the same list y[0] = 0 print(x[0]) # Output: 0Copy by value:
y = x[:] # new copy but nested objects are still references to the items in the original list z = x.copy() # new copy but nested objects are still references to the items in the original list w = list(x) # new copy but nested objects are still references to the items in the original list y[0] = 'a' z[0] = 'b' w[0] = 'c' print(x[0]) # Output: 0 print(y[0]) # Output: a print(z[0]) # Output: b print(w[0]) # Output: c # replacing the entire nested object reference does NOT affect the original object y[2] = [6, 7] print(x[2]) # Output: [3, 4] # nested objects are references and hence updates affect the original value z[2][1] = 5 print(x[2]) # Output: [3, 5]Deep copy: create complete new list including nested objects
import copy y = copy.deepcopy(x) y[2] = ['a', 'b'] print(x[2]) # Output: [3, 5] print(y[2]) # Output: ['a', 'b']
x = [1, 2, 0, 9, 8, 7] # length print(len(x)) # Output: 6 # min print(min(x)) # Output: 0 # max print(max(x)) # Output: 9 # sum print(sum(x)) # Output: 27 # counting occurrences of an element print(x.count(9)) # Output: 1 # check if all elements are true (0 isn't) print(all(x)) # Output: False # check if all elements are true with conditions print(all(i > 1 for i in x)) # Output: False # check if any element is true print(any(x)) # Output: True # check if any element is true with conditions print(any(i > 1 for i in x)) # Output: True