# MLE - Week 2 Summary ------- - Collections: *List* (mentioned in [Week 1](https://hackmd.io/@qhoang/S1bHJG7V_)), Tuple, Set, Dictionary - Collection comparisons - Function - *while* Loop (mentioned in [Week 1](https://hackmd.io/@qhoang/S1bHJG7V_)) - Others Tuple ----- :point_right: Tuples are **immutable** sequences, typically used to store collections of *heterogeneous data* [[2]] In another word, the *tuples* are useful when we need an immutable object to be stored in the [Set](#Set) or [Dictionary](#Dictionary) keys. >Tuples may be constructed in a number of ways [[2]]: >- Using a pair of parentheses to denote the empty tuple: **()** >- Using a trailing comma for a singleton tuple:**a**, or **(a,)** >- Separating items with commas: **a, b, c** or **(a, b, c)** >- Using the tuple() built-in: **tuple()** or **tuple(iterable)** Example: ```python= >>> type(('hello',)) <class 'tuple'> >>> type(('hello')) <class 'str'> ``` :penguin: **Allow duplicates**: since tuple are indexed, tuples can have items with the same value. [[3]] ```python= thistuple = ("apple", "banana", "cherry", "apple", "cherry") ``` | Method | Description | | ------- | --------------------------------------------------------------------------------------- | | count() | Returns the number of times a specified value occurs in a tuple | | index() | Searches the tuple for a specified value and returns the position of where it was found | :penguin: [Python Tuple Methods](https://www.w3schools.com/python/python_ref_tuple.asp) Set --- > :point_right: A set object is an **unordered** collection of distinct [hashable](#Hashable) objects. :penguin: `set` is mutable. `frozenset` is an [immutable](#Immutable) set. > Sets can be created by several means [[8]]: > - Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}` > - Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}` > - Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])` ### Methods | Method | Description | | ----------------------------- | ------------------------------------------------------------------------------ | | add() | Adds an element to the set | | clear() | Removes all the elements from the set | | discard() | Remove the specified **item** | | remove() | Removes the specified **element** | | pop() | Removes an element from the set | | copy() | Returns a copy of the set | | difference() | Returns a set containing the difference between two or more sets | | intersection() | Returns a set, that is the intersection of two other sets | | issubset() | Returns whether another set contains this set or not | | issuperset() | Returns whether this set contains another set or not | | union() | Return a set containing the union of sets | :penguin: [Python Set Methods](https://www.w3schools.com/python/python_ref_set.asp) Dictionary ---------- :point_right: Like a *list*, a dictionary is a mutable collection of many values (key-value pair). :penguin: Dictionaries can still **use integer values as keys**, just like lists use integers for indexes, but they do not have to start at 0 and **can be any number**. [[5]] ```python= >>> spam = {12345: 'Luggage Combination', 42: 'The Answer'} ``` ### Dictionary view objects > :point_right: There are three dictionary methods that will return list-like values of the dictionary’s keys, values, or both keys and values: `keys()`, `values()`, and `items()`. [[5]] :exclamation: The values returned by these methods (`dict_keys`, `dict_values`, and `dict_items`, respectively) are view objects and **not true lists**: they **cannot** be modified and do not have an `append()` method. Any [hashable](#Hashable) objects can be the dictionary keys. ### Methods | Method | Description | | -------- | --------------------------------------------------------- | | items() | Returns a list containing a tuple for each key value pair | | keys() | Returns a list containing the dictionary's keys | | values() | Returns a list of all the values in the dictionary | | clear() | Removes all the elements from the dictionary | | pop() | Removes the element with the specified key | :penguin: [Python Dictionary Methods](https://www.w3schools.com/python/python_ref_dictionary.asp) Comparison ---------- :penguin: Goups of data types: - `Sequence Types` — list, tuple, range - `Text Sequence Type` — str - `Set Types` — set, frozenset - `Mapping Types` — dict | Operation / Characteristic | List | Tuple | Set | Dictionary | Remarks| | ---------- | ------------------ | ------------------ | ------------------ | ------------------ |---| | `x` in `s` | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |Check if `x` in `s`| | `x + t`|:heavy_check_mark:|:heavy_check_mark:|:x:|:x:|Concatenation| |`s * n`|:heavy_check_mark:|:heavy_check_mark:|:x:|:x:|Replication| |`s[i]`|:heavy_check_mark:|:heavy_check_mark:|:x:|:x:|Indexing| |`s[i:j:k]`|:heavy_check_mark:|:heavy_check_mark:|:x:|:x:|Slicing| |`len(s)`|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:|:heavy_check_mark:|Get length| |`s.count(x)`|:heavy_check_mark:|:heavy_check_mark:|:x:|:x:|Count element `x`| |Immutable|:x:|:heavy_check_mark:|:x:|:white_check_mark:| For `Dictionary`, only keys are immutable| |Ordered|:heavy_check_mark:|:heavy_check_mark:|:x:|:x:| Since Python`3.7`, `Dictionary` order is guaranteed to be insertion order [[4]]. The dictionaries are still unordered, as you can’t access items in them using integer indexes.| |Allow duplicates|:heavy_check_mark:|:heavy_check_mark:|:x:|:x:|| |Any data types|:heavy_check_mark:|:x:|:x:|:x:|`Tuple`, `Set` and `Dictionary` keys allow only hashable data types.| Function -------- :point_right: Function objects are created by function definitions. :point_right: Methods are functions that are called using the attribute notation. :exclamation: Function has to be defined before using. Others ------ ### *for* Loop vs *while* Loop Use *for* loop when you know exactly the number of the loops. :point_right: Should use *for* loop in most of the cases. Only use the *while* loop when the condition is unknown and determined at the runtime. ### Hashable :point_right: An object is **hashable** if it has a hash value which **never changes** during its lifetime.[[6]] | Data types | Hashable | Remarks | | ---------------------------------------------------- | ------------------ | -------------------------------------------- | | Immutable built-in objects | :heavy_check_mark: | | | Mutable containers (such as lists or dictionaries) | :x: | | | Immutable containers (such as tuples and frozensets) | :heavy_check_mark: | Only hashable if their elements are hashable | | Objects which are instances of user-defined classes | :heavy_check_mark: | | ### Immutable :point_right: An object with a fixed value. Immutable objects include numbers, strings and tuples. [[7]] :penguin: [Glossary](https://docs.python.org/3/glossary.html#glossary) ### Enumerate() :point_right: The enumerate() method adds counter to the iterable. The returned object is a enumerate object. [[1]] Example: ```python= days= { 'Mon', 'Tue', 'Wed','Thu'} enum_days = enumerate(days) # enumearte using loop for enum_days in enumerate(days): print(enum_days) for count,enum_days in enumerate(days,5): print(count,enum_days) ``` Output: ```python= (0, 'Thu') (1, 'Tue') (2, 'Wed') (3, 'Mon') 5 Thu 6 Tue 7 Wed 8 Mon ``` [1]: https://www.tutorialspoint.com/enumerate-in-python [2]: https://docs.python.org/3/library/stdtypes.html#tuples [3]: https://www.w3schools.com/python/python_tuples.asp [4]: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict [5]: https://automatetheboringstuff.com/2e/chapter5/ [6]: https://docs.python.org/3/glossary.html#term-hashable [7]: https://docs.python.org/3/glossary.html#term-immutable [8]: https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset ###### tags: `mle` `week2` `basics` `dictionary` `function` `set` `tuple`