Lists, indexing and slicing and operators | |
A list is a sequence of items. | A = [4, 12, -5.5] |
The elements of a list can be of any type | B = [4, "Is it really?", True] |
Lists can contain lists as elements (sometimes we use the term "sublists") | C = ['a sublist is
next:', ["yup", "this is", 1]] D = [1, [2, 3, [5, 6]], 4] |
The len() function counts the number of elements in a list. Actually the number of "top-level" elements. See the example: | len(A) → 3 len(B) → 3 len(C) → 2 len(D) → 3 |
You can access elements inside a list in the same way you do in a string: indexing by position | A[0] → 4 B[-1] → True C[1] → ["yup", "this is", 1] D[3] → IndexError: list index out of range |
List slicing works the same way as it does for strings. | A[1:3] → [12, -5.5] B[2:15] → [True] C[::-1] → [["yup", "this is", 1], 'a sublist is next:'] D[3:5] → [] |
As you can see, the empty list [] is a valid list, just like the empty string "". | len([]) → 0 |
You can index deeply into lists with sublists. And combine indexing with slicing. | D[1] → [2, 3, [5, 6]] D[1][0] → 2 D[1][2] → [5, 6] D[1][2][1] → 6 D[1][::-1] → [[5, 6], 3, 2] D[1][::-1][1] → 3 |
You don't need to put lists into variables to do indexing or slicing on them -- you can do that on literal lists (though you rarely want to do that, except to show that it can be done). You can also do this with strings. | [1,3,['Hello', 'there']][2][1]
→ 'there' 'Hi there'[3:6] → 'the' |
You can use the "+" to merge lists, just like strings. | A + D → [4, 12, -5.5, 1, [2, 3, [5, 6]], 4] |
You can use * to repeat elements, just like strings (sort of). | [1, 2]*3
→ [1, 2, 1, 2, 1, 2] [[1, 2]]*3 → [[1, 2], [1, 2], [1, 2]] |
Differences between strings and lists | |
Strings are "immutable". That means that they cannot be changed. You can create a new string from an old one, but you cannot change the old one. | P = "Hi there" Q = P[:2]+P[3]+P[2]+P[4:] # Q → 'Hit here' P[0] = 'a' → TypeError: 'str' object does not support item assignment |
List are mutable. You can replace elements of a list or slices of a list with just about anything (no elephants) | E = [0, 1, 2, 3, 4] E[1] = 98 # E → [0, 98, 2, 3, 4] E[1] = ['hi', 'there'] # E → [0, ['hi', 'there'], 2, 3, 4] E[1:3] = [] # E → [0, 3, 4] E[0:2] = ['one', 'two', 'there'] # E → ['one' 'two' 'there', 4] E[1:3] = 'a' # E → ['one', 'a', 4] |