Foundations for efficiencies
Pythonic: Code that executes quickly for the task at hand, minimizes the memory footprint and follows Python’s coding style principles.
Example:
1 | # Collect the names in the above list that have six letters or more. |
- Python Standard Library
(1) Built-in types:list
,tuple
,set
,dict
, and others
(2) Built-in functions:print()
,len()
,range()
,round()
,enumerate()
,map()
,zip()
, and others
(3) Built-in modules:os
,sys
,itertools
,collections
,math
and others
Examples:
- range()
1 | # Create a range object that goes from 0 to 5 |
- enumerate()
1 | # Rewrite the for loop to use enumerate |
- map()
1 | # Use map to apply str.upper to each element in names |
- zip()
combine multiple objects together. It allows us to easily combine two or more objects. If we provide zip() with objects of differing lengths, it will only combine until the smallest lengthed object is exhausted.
NumPy arrays
- Numpy array makes every element the same type
- Mathematical operations are broadcasted to each element of a numpy array by default.
NumPy’s broadcasting concept: broadcasting refers to a numpy array’s ability to vectorize operations, so they are performed on all elements of an object at once.
1 | # Print second row of nums |
Exercise:
1 | # Create a list of arrival times |
Examing the runtime
- Unpacking the range object was faster than list comprehension.
1 | # Create a list of integers (0-50) using list comprehension |
Using Python’s literal syntax to define a data structure can speed up your runtime. Consider using the literal syntaxes (like [] instead of list(), {} instead of dict(), or () instead of tuple()), where applicable, to gain some speed.
Numpy is more efficient than Array