list.extend()¶We can append multiple elements at the same time using list.extend.
L = [42, 43, 45]
M = [51, 52]
L.extend(M)
L
Of course, we can just repeatedly use append instead:
def my_extend(L, M):
'''extend the list L using M'''
for e in M:
L.append(e)
L = [42, 43, 45]
M = [51, 52]
my_extend(L, M)
L
Note that we cannot use append here directly:
L = [42, 43, 45]
M = [51, 52]
L.append(M)
L
What happenned is that we append M as an element, so that the last element of L is the list [51, 52]. This is different from the last two elements of M being [51, 52].
We can use the following in order to "insert" several elements at once in the middle of a list.
L = [42, 43, 45]
M = [51, 52]
L[1:1] = M
L
list.sort() and sorted()¶Here is how we can sort lists in ascending order.
L = [5, 2, 10, 20, 1]
sorted(L)
The value of sorted(L) is a list with the same elements as L, except sorted in ascending order. Note that sorted(L) has a value, but doesn't modify L.
L
L is still unchanged! We can of course go
M = sorted(L)
M
M will be the sorted version of L.
We can also use list.sort()
L
L.sort()
L
L.sort() modifies L to be the sorted (in ascending order) version of L. Note that L.sort()'s value is None:
You can sort lists of strings as well. Those are sorted in alphabetical (called, lexicographical) order:
L = ["CSC", "CIV", "PRA", "ESC"]
sorted(L)
You cannot mix strings and numbers, since you cannot compare them (at least not without additional work)
1 < "one"
sorted([2, "two", "hello"])
L = [3, 1, 5]
M = L.sort()
print(M)
Functions like list.insert(), list.append(), list.sort(), etc all modify lists, and return None. On the other hand, len() and sorted() return a value, but do not modify the argument.
If you add lists to each other, the expression with the addition does have a value
L1 = [1, 2]
L2 = [5, 6, 7]
M = L1 + L2
M
L1
Here, L1 + L2 does have a value. Note that, due to a design quirk, in Python, +=, as applied to lists, works exactly like extend (more on this later.)
L1 = [1, 2]
L2 = [5, 6, 7]
L1 += L2
L1