Python Part3: Bytes, Lists, Shallow copies and Dictionaries
Bytes
- Immutable sequence of bytes.
Lists
- Mutable sequences of objects.
- Get or set value using index
- e.g a[1] = 20 and print(a[1])
- Negative integers index from the end.
- The last element is at index -1
- Slicing extracts part of a list.
- Slice range is half open-stop not included.
- >>> s = [1, 2, 3, 4, 5, 6]
- >>> s[1:4]
- 2, 3, 4
- Slicing works with negative indexes.
- Omitting the stop index slices to the end.
- Slice_to_end = seq[start:]
- Omitting the start index slices from the beginning.
- Slice_from_beginning = seq[:stop]
- Half open ranges give complementary.
- slices
S[:x] + s[x:] == s
- Omitting the start and stop indexes slices from beginning to the end – a full slice.
- Important idiom for copying lists:
- Copy list using
- Copy() method
- List() constructor
- All of these techniques create shallow copies, mean create new list containing same object reference to source list.
Shallow copies: Examples
-
>>> A = [[1, 2], [3, 4]]
- >>> B = A[:] (copy using full slice)
- >>> A is B (both objects have different identities.)
- >>> A == B
- >>> A[0]
- >>> B[0]
- A[0] is B[0] (both objects have same identities.)
- >>> A[0] = [8, 9] (This create a new list and set reference of A[0] to this.)
- >>> A[0]
- >>> B[0] (B[0] is unchanged because it has reference to old list.)
- >>> A[1].append(5) (A[1] and B[1] still have reference to same list. So changes reflects in both places.)
- >>> A[1]
- >>> B[1]
- >>> A (Now both lists look like this)
- >>> B
- Repeat lists using the * operator.
- Most often used for initializing a list of known size with a constant.
- Multiple references to one instance of the constant in the produced list.
- Repetition is shallow.
- >>> S = [[1, 2]] * 5
- [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]
- >>> S[3].append(7)
- >>> S
- [[1, 2, 7], [1, 2, 7], [1, 2, 7], [1, 2, 7], [1, 2, 7]]
- Index(item) returns the integer index of the first equivalent element raises value error if not found.
-
Count(item) returns the number of matching elements.
- The in and not in operators test for membership.
- 5 in [1, 2, 3]
- 5 not in [1, 2, 3]
- Del seq[index] to remove by index.
- Seq.remove(item) to remove by value. Raises value error if not found.
- Insert items with seq.insert(index, item)
- Concatenate lists with + operator
- >>> M = [1, 2]
- >>> N = [3, 4]
- >>> K = m + n
- >>> k
-
In-place extension with += operator or extend method.
- >>> K += [6, 7]
- >>> K
- >>> K.entend([11, 12])
- >>> K
- [1, 2, 3, 4, 6, 7, 11, 12]
- K.reverse() reverses in place.
- K.sort() sorts in place.
- K.sort(reverse=true) gives descending sort.
Dictionaries
-
Unordered mapping from unique, immutable keys to mutable values.
- Recap literals:
- Delimited by { and }
- Key-value pairs comma separated
- Corresponding keys and values joined by colon.
- Keys must be unique
- Urls = {'google':'http://google.com', 'microsoft':'http://Microsoft.com' }
- >>> url['google']
- Dict() constructor accepts:
- Iterable series of key-value 2-tuples.
- >>> Names_and_ages = [('Alice', 32), ('Bob', 48)]
- >>> d = dict(Names_and_ages)
- >>> d
- Keyword arguments-requires keys are valid python identifiers.
- A mapping, such as another dict.
- >>> Phonetic = dict(a='alfa', b='bravo')
- >>> phonetic
- {'a':'alfa', 'b':'bravo'}
-
d.copy() for copying dictionaries.
- Or simply dict(d) constructor
-
Extend a dictionary with update()
- >>> g = dict('c':'charle', 'f':'fort')
- >>> f.update(g)
- >>> f
- {'a':'alfa', 'b':'bravo', 'c':'charle', 'f':'fort'}
- Update replaces values corresponding to duplicate keys.
- Iteration is over keys.
- Get corresponding value with d[key] lookup.
- >>> for key in f:
- print("{key} => {value}".format(key= key, value=f[key]))
- Use values() for an iterable view onto the series of values
- No efficient way to get the key corresponding to a value.
- >>> for value in f.values():
- print(value)
-
Keys() method gives iterable view onto keys – not often needed.
- >>> for key in f.keys():
- print(key)
- Use items for an iterable view onto the series of key-value tuples.
- Use with tuple unpacking.
- >>> for key, value in f.items():
- print("{key} => {value}".format(key=key, value=value))
- The in and not in operators work on the keys.
- >>> 'a' in f
- >>> 'h' in f
-
Use del keyword to remove by key. del d[key]
- Keys must be immutable.
- Values may be mutable.
- The dictionary itself is mutable.
See Also
No comments:
Post a Comment