Writing Efficient Python Code Flashcards
Two ways to create a list from a range object. Use nums = range(6)
nums_list = list(nums)
nums_list = [*range(6)]
* unpacks the range object
names = [“Jerry”, “Kramer”, “Elaine”]
What does enumerate(names) do?
How do you make the index start at a different number than 0?
It creates an indexed list
enumerate(seq, num)
num is the desired start number
How can you unpack an enumerate object into a list?
Use names = [“Jerry”, “Kramer”, “Elaine”]
Use *
indexed_names_list = [*enumerate(names)]
The list will be [(0, “Jerry”), (1, “Kramer”), (2, “Elaine”)
How do you print a list from a map object?
print(*map(function, seq))
What magic function can you use to estimate runtime?
Syntax with option to specify number of runs and loops
with a single line of code
with multiple lines of code
%timeit -rnum1 -nnum2 code
num1 is the number of runs
num2 is the number of loops per run, loops are executions of the code
For multiple lines of code:
%%timeit
Syntax to save the output of %timeit into a variable.
How can you view the time for each run, the best overall time and the worst overall time?
times = %timeit -o code
times. timings
times. best
times. worst