Writing Efficient Python Code Flashcards

1
Q

Two ways to create a list from a range object. Use nums = range(6)

A

nums_list = list(nums)

nums_list = [*range(6)]

* unpacks the range object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

names = [“Jerry”, “Kramer”, “Elaine”]

What does enumerate(names) do?

How do you make the index start at a different number than 0?

A

It creates an indexed list

enumerate(seq, num)

num is the desired start number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can you unpack an enumerate object into a list?

Use names = [“Jerry”, “Kramer”, “Elaine”]

A

Use *

indexed_names_list = [*enumerate(names)]

The list will be [(0, “Jerry”), (1, “Kramer”), (2, “Elaine”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you print a list from a map object?

A

print(*map(function, seq))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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

A

%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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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?

A

times = %timeit -o code

times. timings
times. best
times. worst

How well did you know this?
1
Not at all
2
3
4
5
Perfectly