My learning journey — Python [Part 3]
2 min readJun 5, 2019
Tuples
- tuple = (element1, element2,…)
- an immutable ordered collection / grouping of items
- advantages of using tuples: faster than list, safer
- tuples can be used as dictionary key, example coordinates as key (x, y). List cannot be used as dict key
- for <item> in <tuple>: loop through the tuple
- tuple[<index>]: access a particular item by index
- tuple.count(<item>): count the number of times an item in tuple
- tuple.index(<item>): gives the index of first occurrence of item (error if not exist)
- slicing works
- nested tuples are possible
- tuple = (<item>,): creating a tuple with 1 element
- tuple = tuple(<collection>): creating a tuple out of a collection
Sets
- Unordered, unique collection of items
- s={element1, element2, …}
- <item> in s: return true/false of whether item is in s
- set(<list>): converting a list into a set
- list(<set>): creating a unique list of items
- set.add(<item>): add an item
- set.remove(<item>): removes an item. give error if item not there
- set.discard(<item>): remove items without error if not exist
- set.copy(): create a copy of a set (not the same in memory)
- set1 is set2: check if the 2 sets are same in memory
- set.clear(): remove all elements in set
- set1 | set2: return a set with union of the 2 sets
- set1 & set2: return a set with intersection of the 2 sets
- {op for x in <collection>}: create a set going through operation in collection e.g. {x**2 for x in range(0:9)}
Functions
- def name_of_function(<input>): — defining a function
- return <something>: to return something from the function
- def name_of_function(<input>=<default parameter>): to specify a default value for a parameter (parameter can be a function)
- name_of_function(<keyword>=<value>, …): to explicitly declare the argument to be assigned the value for when calling a function. (allows defying the order of which the function arguments were defined)
- global <variable>: to specify in a function accessing and making changes a variable that is defined in the global scope (no need if you are not changing the value)
- nonlocal <variable> : to specify in a function accessing and making changes a variable that is defined in the outer function scope (no need if you are not changing the value)
- <function>.__doc__: to access documentation of a function
- “””function description”””: declare your own documentation for a function in the first line of the function
- name_of_function(*args): define a tuple of arguments to be passed in
- name_of_function(**args): pass dictionary of arguments to function (call: func1(arg=’heythere’)
- order of parameters for functions: parameters, *args, default parameters, **kwargs
- name_of_function(*<list/tuple>): unpack a list or tuple into a list of arguments to pass in a function expecting a series of arguments
- name_of_function(**<dictionary>): unpack a dictionary into dictionary of arguments to pass to a function expecting **kwargs