Python Flashcards
Strings mutable?
No, immutable. If you want to concat a bunch of strings without creating a new string for each intermediate operation, use ““.join(list)
Returns true if all char are alphanumeric (and at least one char)
isalnum()
Returns true if all char are letters (and at least one char)
isalpha()
Returns true if all char are digits (and at least one digit)
isdigit()
Returns a string which is a concatenation of the strings in a list (or other iterable)
join
““.join
Split a string on whitespace, ignore empty strings
split no param
That means splitting an empty string will return an empty list
Split a string on whitespace, include empty string
split(‘ ‘)
Remove leading and trailing whitespace
strip
Add an element to list
append
If you’re trying to create a list of lists, use append rather than +=
Combine two lists
+ or += joins two lists into a single list
append adds a single element to a list. that’s why you want to use append to compose a list of lists.
extend is an in-place function call so you should return the original list
set operations
set()
add, remove
list pop no argument
removes the last item in the list
get k,v from map
items()
Returns a dict_items object which is not accessible via index.
Need to use operator.getitem()
sort
list.sort(). returns None. operates on a list, in place, stable, does not return new list b/c it’s an in place sort, key arg takes a fn that extracts a comparison key
convert comparator to key
func_tools.cmp_to_key
sorted
sorted(list)
built in method.
returns new sorted list.
stable.
key arg takes a function that extracts a comparison key from a single element.
sorted(list, key=len)
sorted(list, key=abs)
class defn
The purpose of the init method is to initialize the object’s attributes. Used in classes only.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
return the key corresponding to the max val in a freq map
max(freq_map.items(), key=operator.itemgetter(1))[0]
f = operator.itemgetter(2)
what does f(‘ABC’) return
Returns C, the item at index 2
g = operator.itemgetter(2, 5, 3)
what does g(‘ABCDEF’) return?
Returns a list with the items at indicies 2, 5, and 3
(‘C’, ‘F’, ‘D’)