Share
Embed
ChennaiPy - Jan 2017
Anna
January 29, 2017
Transcript
27 slides
-
My new year resolutions: • PEP 8 • PEP 20
• PEP 257 • Idiomatic python • Testing (just kidding!) -
PEP 8 • https://www.python.org/dev/peps/pep-0008/ • Style guide for python code
• Do I use tabs or spaces for indentation? • How to name your variables and methods etc. • Pylint, pep8, pyflakes PEP = Python Enhancement Proposal -
PEP 20 • https://www.python.org/dev/peps/pep-0020/ • The Zen of Python •
“Long time Pythoneer Tim Peters succinctly channels the BDFL (Benevolent Dictator For Life) guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.” • An aphorism - “a concise statement of a scientific principle, typically by a classical author.” • python -c 'import this' • https://www.quora.com/What-do-different-aphorisms-in-Th e-Zen-of-Python-mean -
The Zen of Python Beautiful is better than ugly. …
Readability counts. … There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. -
in, not in In, not in • Calls __contain__ •
Dictionaries - check for a given key. • Strings - x is a substring of y • Faster and pythonic • Readable -
if foo is better than if foo != []: •
Similar to == and != • Faster and pythonic • Readable -
Swapping values z = 1 y = 2 y, z
= z, z+y y = 1 z = 3 -
Unpacking sequences a = [1,2,3,4] var1, var2, var3, _ =
a a, *rest = [1, 2, 3] a, *middle, c = [1, 2, 3, 4] -
Looping backwards for i in reversed(colors): print(i) reversed(seq) Return a
reverse iterator. seq must be an object which has a __reversed__() method -
Looping over lists for i, item in enumerate(colors): print(i, item)
enumerate(iterable, start=0) Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. -
Looping over a sorted list for color in sorted(colors): print
colors sorted(iterable[, key][, reverse]) Return a new sorted list from the items in iterable. key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly). -
Looping with range class range(start, stop[, step]) • Takes up
less memory • Closest thing to a for loop “ -
Does this key exists in the dictionary? dictionary.get("some_key", None) •
This won’t throw an error like dict[“key”] Even better… dictionary.setdefault("some_key", default=None) • Inserts a key with the default value -
Iterating over keys dict = {'r': 'red', 'b':'blue', 'c':'cyan'} for
i in dict: print(i) If you’re going to be changing the values of the keys for i in dict.keys(): del dict[i] -
Iterating over keys over keys & values in a dictionary
for k, v in dict.items(): print(k, '--->', v) -
Sum an array with list comprehensions “A list comprehension consists
of brackets containing an expression followed by a for clause, then zero or more for or if clauses." [ expr for var1 in list1 if/for… ] a = [i + 3 for i in range(10)] • Clean and readable • Avoid for complex expressions - use loops -
Concatenating strings “”.join(list_of_strings) str.join(iterable) Return a string which is the
concatenation of the strings in the iterable iterable. • Effective for large strings • Avoid + try to use .format() -
Use the right data structures #Lists # O(N) del names[0]
# O(N) names.pop(0) # O(N) names.insert(0, 'Anna') -
Faster # More efficient with deque # O(1) del names[0]
# O(1) names.popleft() # O(1) names.appendleft('mark') -
Generators & Generator Expressions • Lazy loading • Save memory
• Iterate only once • Easier way to make iterators • Yield similar to return - returns a generator object a = (i + 3 for i in range(10)) -
Default arguments values • Do not use mutable objects! ◦
list ◦ dict ◦ set