Class 2: Iterables
Jump to navigation
Jump to search
BIOF 309 Curriculum - back to main
Contents
Lists
- list - items in list can be heterogenous
a_list = [1, 2, 3, "a dog"]
empty_list = []
- declared by bracket outside, comma delimited within
Tuples
- tuple - immutable list
- comes from math concept, quadruple, quintuple, sextuple, ... n-tuple
a_tuple = 1, 2, 3, "four"
readable_tuple = ( 1, 2, 3, "four" )
empty_tuple = ()
- unpacking:
the_tuple = (45,67,'hello'); val1, val2, val3 = the_tuple
Dicts
- dict = dictionary = hash = map
- syntax = {key: value}
- can declare multiple keys/values in one statement using "key" : value syntax
a_dictionary = {"key 1":"value 1", 2:3, 4:[]}
Sets
- set
- unindexed, unordered, contains no duplicates
- the set itself is mutable, but can only put immutable things in a set
- operations like union, intersection, etc.
some_set = {0, (), False}
empty_set = set() # not {}, this is a dictionary
- To create a set of sets, use frozenset()
immutable_set = frozenset...
Strings
- string - immutable
Other Iterables
- deque - efficient pushes & pops from both ends.
- from collections import deque
- q = deque( [ ... ] )
- q.append()
- q.popleft()
Converting Between Iterable Types
In [1]: tupp = ('a', 1), ('b', 2), ('c',3), ('d',4) In [2]: type(tupp) Out[2]: tuple In [3]: dictt = dict(tupp) In [4]: dictt Out[4]: {'a': 1, 'b': 2, 'c': 3, 'd': 4} In [5]: dictt.items() Out[5]: [('a', 1), ('c', 3), ('b', 2), ('d', 4)] In [6]: tuppp = enumerate(tupp) In [7]: tuppp Out[7]: <enumerate at 0x1019aad20> In [8]: dict(tuppp) Out[8]: {0: ('a', 1), 1: ('b', 2), 2: ('c', 3), 3: ('d', 4)} In [9]: tupp = [('a', 1), ('b', 2), ('c',3), ('d',4)] In [10]: dictt = dict(tupp) In [11]: dictt.items() Out[11]: [('a', 1), ('c', 3), ('b', 2), ('d', 4)]
- Converting between list of characters and strings
Using Iterables
x in s
- true/false, substring testx not in s
- true/false, substring tests + t
- concatenation, could be costly, use str.join()s * n, n * s
- n shallow copies of s concatenated. Modify s and all n copies will be changed.s[i]
- ith item of s, origin 0. If i is negative, index is relative to end of strings[i:j]
- slice of s from i to j- Truncate:
s[:25]
- take first 25 items
- Truncate:
s[i:j:k]
- slice of s from i to j with step k- index from the back using negative
- deep copy - [:]
len(s)
- length of iterablemin(s)
max(s)
s.index(i)
- index of first occurrence of i in ss.count(i)
- total number of occurrences of i in slist.append(item)
- list.extend( another_list )
- list.insert( position_index, value )
- list.remove( value ) - removes first instance of value from list
- list.pop() - remove last item from list and return it
- list.pop(i) - remove the ith item in the list and return it
- list.count( value ) - ## times value appears in list
- list.reverse()
- del
- sort()
- .append()
- subset
- dict.keys(), dict.values()
- truth value testing : all(), any()
Fun with Strings
- escape characters
- concatenation +
- split() and join()
- ends with
- rawstring - to avoid backslash hell
- str.capitalize()
- str.center(width[, fillchar]) - padding is done with fillchar, default is space
- str.count( substr[, start, end])
- str.endswith( suffix[ start[, end]]) - suffix can also be a tuple of strings to look for
- str.statrswith(...)
- str.expandtabs( tabsize = 8)
- str.find(substr[, start[, end]]) - use only if you need to know position of substr, otherwise use in operator. returns lowest index where substr is found.
- str.rfind(...) start from the right
- str.index() - like find, but raise ValueError exception if substr not found
- str.rindex() - from the right
- str.format( *args, **kwargs )
- str.isalnum() - all chars alphanumeric, and at least 1 char
- str.isdigit()
- str.islower()
- str.isupper()
- str.isspace() - whitespace
- str.join( iterable)
- str.lower()
- str.upper()
- str.strip( [chars] )
- str.lstrip( [chars = "whitespace"]) - strip chars from beginning of string
- str.rstrip()
- str.partition( sep ) - return 3-tuple of before, sep, after
- str.rpartition(...)
- str.replace(old, new[, count])
- str.split([sep[, maxsplit]]) - if sep is None, separator is whitespace
- str.splitlines( [keepends = false])
- str.swapcase()
- str.translate( table[, deletechars])
- str.zfill(width) - zerofill
- If you need to include a brace character in the literal text, it can be escaped by doubling: Template:And