Python | Basics | Priority Flashcards
What is the fastest way to reverse a string?
backward = text[::-1]
https://datagy.io/python-reverse-string/
vars()
Returns the __dict__ attribute for a module, class, instance, or other object that has a __dict__ attribute. Let’s say you only wanted to print the object’s instance attributes as well as their values, we can use the vars() function.
dir()
Without any arguments, the function returns the list of names in the current local scope. If an argument is passed in, returns a list of valid attributes for that object. Prints out of all the attributes of a Python object, including the ones that are defined in the class definition.
How to sort a list of complex record objects by a specific key of a record.
python-data-structures
sorted(animals, key=lambda x: x[specific_key])
How to randomly choose a member of a set.
python-standard-library
import random random.choice(set)
Example of how to get the sum of squares of ints with constant time complexity.
python-data-structures
sum((i * i for i in range(1, 1001)))
Example of how to get an item from a dict with a default.
python-data-structures
name = cowboy.get('name', 'The Man with No Name')
Example of how to set a default in a dict.
python-data-structures
name = cowboy.setdefault('name', 'The Man with No Name')
How to initialize a dict with list values.
python-standard-library
from collections import defaultdict; student_grades = defaultdict(list)
Example of how to: get the frequencies of words in a list: get the most frequent k words.
from collections import Counter; counts = Counter(words); counts.most_common(k)
List several string constants.
string.ascii_letters
string.ascii_uppercase
string.ascii_lowercase
string.digits
string.hexdigits
string.octdigits
string.punctuation
string.printable
string.whitespace
Example of how to get permutations from a list.
list(itertools.permutations(friends, r=2))
Simplifies exception handling by encapsulating
standard uses of try/finally statements in so-called context
managers.
2.3 p35