ᚱᛗ
© 2022
Powered by Hugo

Methods on Lists

Table of Contents

list.append(x)

Add an item x to the end of the list.

a = [1, 2, 3, 4, 5]
x = 100  # integer
a.append(x)
print(a)  # [1, 2, 3, 4, 5, 100]
assert a[len(a) - 1 :] == [x]
b = ["s1", "s2"]  # iterable
a.append(b)
print(a)  # [1, 2, 3, 4, 5, 100, ['s1', 's2']
assert a[len(a) - 1 :] == [b]

list.extend(iterable)

Extend the list by iterating over and appending all the items from the iterable

a = [1, 2, 3, 4, 5]
b = [100, 200, 300]
a.extend(b)
print(a)  # [1, 2, 3, 4, 5, 100, 200, 300]

list.insert(i, x)

At position i, insert item x

a = [1, 2, 3, 4, 5]
s = "a_string"
b = ["an", "iterable"]
a.insert(0, s)  # insert at the beginning
print(a)  # ['a_string', 1, 2, 3, 4, 5]
a.insert(len(a), b)  # insert at the end
print(a)  # ['a_string', 1, 2, 3, 4, 5, ['an', 'iterable']]
mid_element = len(a) // 2
a.insert(mid_element, "median")  # insert at the middle
print(a)  # ['a_string', 1, 2, 'median', 3, 4, 5, ['an', 'iterable']]

list.remove(x)

Remove only the first instance of x (in place, nothing returned)

a = [1, 2, 3, 4, 5, "s", "z", "s"]
a.remove("s")
print(a)  # [1, 2, 3, 4, 5, 'z', 's']

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.

a = [1, 2, 3, 4, 5]
a.pop()  # 5
print(a)  # [1, 2, 3, 4]
a.pop(0)  # 1
print(a)  # [2, 3, 4]
mid_element = len(a) // 2
a.pop(mid_element)  # 3
print(a)  # [2, 4]

list.clear()

Remove all items from the list. Equivalent to del a[:]

a = [1, 2, 3, 4, 5]
a.clear()
print(a)  # []

list.count(x)

Return the number of times x appears in the list.

a = ["a", "b", "c"] * 3
print(a)  # ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
x = "b"
a.count(x)  # 3

list.sort(*, key=None, reverse=False)

Sort the items of the list in place

a = [0, 3, 8, 2, 1, 10, 9]
a.sort()
print(a)  # [0, 1, 2, 3, 8, 9, 10]
a.sort(reverse=True)
print(a)  # [10, 9, 8, 3, 2, 1, 0]

When sorting with a key, the order is determined by the return of the lambda function.

b = [3, 4, 0, -4, -3]
cubic = [(x, x ** 3) for x in b]  # (x, f(x)=x^3)
print(cubic)  # [(3, 27), (4, 64), (0, 0), (-4, -64), (-3, -27)]
b.sort(key=lambda x: x ** 3)
print(b)  # [-4, -3, 0, 3, 4]
cubic.sort(key=lambda x: x[1])
print(cubic)  # [(-4, -64), (-3, -27), (0, 0), (3, 27), (4, 64)]
assert b == [c[0] for c in cubic]

list.reverse()

Reverse the elements of the list in place.

a = ["one", "to", "many"]
a.reverse()
print(a)  # ['many', 'to', 'one']

list.copy()

Return a shallow copy of the list. Equivalent to a[:]

a = ["a", "b", "c", "d"]
b = a.copy()  # shallow copy
assert hex(id(a)) != hex(id(b))
assert b == a[:] and b is not a  # same contents, different objects