Python Notes For Professionals
Python Notes For Professionals
Python
Notes for Professionals
®
700+ pages
of professional hints and tricks
Disclaimer
GoalKicker.com This is an unocial free book created for educational purposes and is
not aliated with ocial Python® group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with Python Language ...................................................................................... 2
Section 1.1: Getting Started ........................................................................................................................................... 2
Section 1.2: Creating variables and assigning values ................................................................................................ 6
Section 1.3: Block Indentation ....................................................................................................................................... 9
Section 1.4: Datatypes ................................................................................................................................................. 11
Section 1.5: Collection Types ...................................................................................................................................... 15
Section 1.6: IDLE - Python GUI .................................................................................................................................... 19
Section 1.7: User Input ................................................................................................................................................. 20
Section 1.8: Built in Modules and Functions .............................................................................................................. 21
Section 1.9: Creating a module ................................................................................................................................... 25
Section 1.10: Installation of Python 2.7.x and 3.x ....................................................................................................... 26
Section 1.11: String function - str() and repr() ........................................................................................................... 28
Section 1.12: Installing external modules using pip ................................................................................................... 29
Section 1.13: Help Utility ............................................................................................................................................... 30
Chapter 2: Python Data Types ............................................................................................................................ 32
Section 2.1: String Data Type ..................................................................................................................................... 32
Section 2.2: Set Data Types ....................................................................................................................................... 32
Section 2.3: Numbers data type ................................................................................................................................ 32
Section 2.4: List Data Type ......................................................................................................................................... 33
Section 2.5: Dictionary Data Type ............................................................................................................................. 33
Section 2.6: Tuple Data Type ..................................................................................................................................... 33
Chapter 3: Indentation ............................................................................................................................................. 34
Section 3.1: Simple example ....................................................................................................................................... 34
Section 3.2: How Indentation is Parsed ..................................................................................................................... 34
Section 3.3: Indentation Errors ................................................................................................................................... 35
Chapter 4: Comments and Documentation .................................................................................................. 36
Section 4.1: Single line, inline and multiline comments ............................................................................................ 36
Section 4.2: Programmatically accessing docstrings .............................................................................................. 36
Section 4.3: Write documentation using docstrings ................................................................................................ 37
Chapter 5: Date and Time ...................................................................................................................................... 40
Section 5.1: Parsing a string into a timezone aware datetime object .................................................................... 40
Section 5.2: Constructing timezone-aware datetimes ............................................................................................ 40
Section 5.3: Computing time dierences .................................................................................................................. 42
Section 5.4: Basic datetime objects usage ............................................................................................................... 42
Section 5.5: Switching between time zones .............................................................................................................. 43
Section 5.6: Simple date arithmetic ........................................................................................................................... 43
Section 5.7: Converting timestamp to datetime ...................................................................................................... 44
Section 5.8: Subtracting months from a date accurately ....................................................................................... 44
Section 5.9: Parsing an arbitrary ISO 8601 timestamp with minimal libraries ...................................................... 44
Section 5.10: Get an ISO 8601 timestamp .................................................................................................................. 45
Section 5.11: Parsing a string with a short time zone name into a timezone aware datetime object ................ 45
Section 5.12: Fuzzy datetime parsing (extracting datetime out of a text) ............................................................ 46
Section 5.13: Iterate over dates .................................................................................................................................. 47
Chapter 6: Date Formatting .................................................................................................................................. 48
Section 6.1: Time between two date-times ............................................................................................................... 48
Section 6.2: Outputting datetime object to string .................................................................................................... 48
Section 6.3: Parsing string to datetime object ......................................................................................................... 48
Chapter 7: Enum .......................................................................................................................................................... 49
Section 7.1: Creating an enum (Python 2.4 through 3.3) ......................................................................................... 49
Section 7.2: Iteration ................................................................................................................................................... 49
Chapter 8: Set ............................................................................................................................................................... 50
Section 8.1: Operations on sets .................................................................................................................................. 50
Section 8.2: Get the unique elements of a list .......................................................................................................... 51
Section 8.3: Set of Sets ................................................................................................................................................ 51
Section 8.4: Set Operations using Methods and Builtins ......................................................................................... 51
Section 8.5: Sets versus multisets .............................................................................................................................. 53
Chapter 9: Simple Mathematical Operators ................................................................................................. 55
Section 9.1: Division ..................................................................................................................................................... 55
Section 9.2: Addition .................................................................................................................................................... 56
Section 9.3: Exponentation ......................................................................................................................................... 57
Section 9.4: Trigonometric Functions ........................................................................................................................ 58
Section 9.5: Inplace Operations ................................................................................................................................. 58
Section 9.6: Subtraction .............................................................................................................................................. 59
Section 9.7: Multiplication ........................................................................................................................................... 59
Section 9.8: Logarithms .............................................................................................................................................. 60
Section 9.9: Modulus ................................................................................................................................................... 60
Chapter 10: Bitwise Operators ............................................................................................................................. 61
Section 10.1: Bitwise NOT ............................................................................................................................................ 61
Section 10.2: Bitwise XOR (Exclusive OR) .................................................................................................................. 62
Section 10.3: Bitwise AND ............................................................................................................................................ 63
Section 10.4: Bitwise OR .............................................................................................................................................. 63
Section 10.5: Bitwise Left Shift .................................................................................................................................... 63
Section 10.6: Bitwise Right Shift .................................................................................................................................. 64
Section 10.7: Inplace Operations ................................................................................................................................ 64
Chapter 11: Boolean Operators ............................................................................................................................ 65
Section 11.1: `and` and `or` are not guaranteed to return a boolean ...................................................................... 65
Section 11.2: A simple example ................................................................................................................................... 65
Section 11.3: Short-circuit evaluation ......................................................................................................................... 65
Section 11.4: and ........................................................................................................................................................... 66
Section 11.5: or .............................................................................................................................................................. 66
Section 11.6: not ............................................................................................................................................................ 67
Chapter 12: Operator Precedence ...................................................................................................................... 68
Section 12.1: Simple Operator Precedence Examples in python ............................................................................. 68
Chapter 13: Filter ......................................................................................................................................................... 69
Section 13.1: Basic use of filter .................................................................................................................................... 69
Section 13.2: Filter without function ........................................................................................................................... 69
Section 13.3: Filter as short-circuit check .................................................................................................................. 70
Section 13.4: Complementary function: filterfalse, ifilterfalse ................................................................................. 70
Chapter 14: Arrays ..................................................................................................................................................... 72
Section 14.1: Access individual elements through indexes ....................................................................................... 72
Section 14.2: Basic Introduction to Arrays ................................................................................................................ 72
Section 14.3: Append any value to the array using append() method .................................................................. 73
Section 14.4: Insert value in an array using insert() method .................................................................................. 73
Section 14.5: Extend python array using extend() method ..................................................................................... 73
Section 14.6: Add items from list into array using fromlist() method .................................................................... 73
Section 14.7: Remove any array element using remove() method ....................................................................... 74
Section 14.8: Remove last array element using pop() method .............................................................................. 74
Section 14.9: Fetch any element through its index using index() method ............................................................. 74
Section 14.10: Reverse a python array using reverse() method ............................................................................. 74
Section 14.11: Get array buer information through buer_info() method .......................................................... 75
Section 14.12: Check for number of occurrences of an element using count() method ...................................... 75
Section 14.13: Convert array to string using tostring() method .............................................................................. 75
Section 14.14: Convert array to a python list with same elements using tolist() method .................................... 75
Section 14.15: Append a string to char array using fromstring() method ............................................................. 75
Chapter 15: Dictionary .............................................................................................................................................. 76
Section 15.1: Introduction to Dictionary ..................................................................................................................... 76
Section 15.2: Avoiding KeyError Exceptions .............................................................................................................. 77
Section 15.3: Iterating Over a Dictionary ................................................................................................................... 77
Section 15.4: Dictionary with default values ............................................................................................................. 78
Section 15.5: Merging dictionaries .............................................................................................................................. 79
Section 15.6: Accessing keys and values ................................................................................................................... 79
Section 15.7: Accessing values of a dictionary ......................................................................................................... 80
Section 15.8: Creating a dictionary ............................................................................................................................ 80
Section 15.9: Creating an ordered dictionary ........................................................................................................... 81
Section 15.10: Unpacking dictionaries using the ** operator ................................................................................... 81
Section 15.11: The trailing comma .............................................................................................................................. 82
Section 15.12: The dict() constructor .......................................................................................................................... 82
Section 15.13: Dictionaries Example ........................................................................................................................... 82
Section 15.14: All combinations of dictionary values ................................................................................................ 83
Chapter 16: List ............................................................................................................................................................. 84
Section 16.1: List methods and supported operators ............................................................................................... 84
Section 16.2: Accessing list values .............................................................................................................................. 89
Section 16.3: Checking if list is empty ........................................................................................................................ 90
Section 16.4: Iterating over a list ................................................................................................................................ 90
Section 16.5: Checking whether an item is in a list ................................................................................................... 91
Section 16.6: Any and All ............................................................................................................................................. 91
Section 16.7: Reversing list elements ......................................................................................................................... 92
Section 16.8: Concatenate and Merge lists ............................................................................................................... 92
Section 16.9: Length of a list ....................................................................................................................................... 93
Section 16.10: Remove duplicate values in list .......................................................................................................... 93
Section 16.11: Comparison of lists ............................................................................................................................... 94
Section 16.12: Accessing values in nested list ............................................................................................................ 94
Section 16.13: Initializing a List to a Fixed Number of Elements .............................................................................. 95
Chapter 17: List comprehensions ........................................................................................................................ 97
Section 17.1: List Comprehensions .............................................................................................................................. 97
Section 17.2: Avoid repetitive and expensive operations using conditional clause .............................................. 99
Section 17.3: Dictionary Comprehensions ............................................................................................................... 101
Section 17.4: Generator Expressions ........................................................................................................................ 102
Section 17.5: Set Comprehensions ........................................................................................................................... 104
Section 17.6: Comprehensions involving tuples ...................................................................................................... 104
Section 17.7: Counting Occurrences Using Comprehension ................................................................................. 105
Section 17.8: Changing Types in a List .................................................................................................................... 105
Chapter 18: List slicing (selecting parts of lists) ....................................................................................... 107
Section 18.1: Using the third "step" argument ......................................................................................................... 107
Section 18.2: Selecting a sublist from a list ............................................................................................................. 107
Section 18.3: Reversing a list with slicing ................................................................................................................. 107
Section 18.4: Shifting a list using slicing ................................................................................................................... 107
Chapter 19: Linked lists .......................................................................................................................................... 109
Section 19.1: Single linked list example .................................................................................................................... 109
Chapter 20: Linked List Node ............................................................................................................................. 113
Section 20.1: Write a simple Linked List Node in python ....................................................................................... 113
Chapter 21: Tuple ...................................................................................................................................................... 114
Section 21.1: Tuple ...................................................................................................................................................... 114
Section 21.2: Tuples are immutable ......................................................................................................................... 115
Section 21.3: Packing and Unpacking Tuples ......................................................................................................... 115
Section 21.4: Built-in Tuple Functions ...................................................................................................................... 116
Section 21.5: Tuple Are Element-wise Hashable and Equatable .......................................................................... 117
Section 21.6: Indexing Tuples ................................................................................................................................... 118
Section 21.7: Reversing Elements ............................................................................................................................. 118
Chapter 22: Functions ............................................................................................................................................. 119
Section 22.1: Defining and calling simple functions ............................................................................................... 119
Section 22.2: Defining a function with an arbitrary number of arguments ........................................................ 120
Section 22.3: Lambda (Inline/Anonymous) Functions .......................................................................................... 123
Section 22.4: Defining a function with optional arguments .................................................................................. 125
Section 22.5: Defining a function with optional mutable arguments .................................................................. 126
Section 22.6: Argument passing and mutability .................................................................................................... 127
Section 22.7: Returning values from functions ...................................................................................................... 128
Section 22.8: Closure ................................................................................................................................................. 128
Section 22.9: Forcing the use of named parameters ............................................................................................ 129
Section 22.10: Nested functions ............................................................................................................................... 130
Section 22.11: Recursion limit .................................................................................................................................... 130
Section 22.12: Recursive Lambda using assigned variable .................................................................................. 131
Section 22.13: Recursive functions ........................................................................................................................... 131
Section 22.14: Defining a function with arguments ................................................................................................ 132
Section 22.15: Iterable and dictionary unpacking .................................................................................................. 132
Section 22.16: Defining a function with multiple arguments ................................................................................. 134
Chapter 23: Defining functions with list arguments ............................................................................... 135
Section 23.1: Function and Call ................................................................................................................................. 135
Chapter 24: Functional Programming in Python ..................................................................................... 136
Section 24.1: Lambda Function ................................................................................................................................ 136
Section 24.2: Map Function ...................................................................................................................................... 136
Section 24.3: Reduce Function ................................................................................................................................. 136
Section 24.4: Filter Function ..................................................................................................................................... 136
Chapter 25: Partial functions ............................................................................................................................. 137
Section 25.1: Raise the power ................................................................................................................................... 137
Chapter 26: Decorators ......................................................................................................................................... 138
Section 26.1: Decorator function .............................................................................................................................. 138
Section 26.2: Decorator class .................................................................................................................................. 139
Section 26.3: Decorator with arguments (decorator factory) ............................................................................. 140
Section 26.4: Making a decorator look like the decorated function .................................................................... 141
Section 26.5: Using a decorator to time a function ............................................................................................... 142
Section 26.6: Create singleton class with a decorator .......................................................................................... 143
Chapter 27: Classes ................................................................................................................................................. 144
Section 27.1: Introduction to classes ........................................................................................................................ 144
Section 27.2: Bound, unbound, and static methods .............................................................................................. 145
Section 27.3: Basic inheritance ................................................................................................................................ 147
Section 27.4: Monkey Patching ................................................................................................................................ 149
Section 27.5: New-style vs. old-style classes .......................................................................................................... 149
Section 27.6: Class methods: alternate initializers ................................................................................................. 150
Section 27.7: Multiple Inheritance ............................................................................................................................ 152
Section 27.8: Properties ............................................................................................................................................ 154
Section 27.9: Default values for instance variables ............................................................................................... 155
Section 27.10: Class and instance variables ........................................................................................................... 156
Section 27.11: Class composition .............................................................................................................................. 157
Section 27.12: Listing All Class Members ................................................................................................................. 158
Section 27.13: Singleton class ................................................................................................................................... 159
Section 27.14: Descriptors and Dotted Lookups .................................................................................................... 160
Chapter 28: Metaclasses ....................................................................................................................................... 161
Section 28.1: Basic Metaclasses ............................................................................................................................... 161
Section 28.2: Singletons using metaclasses ........................................................................................................... 162
Section 28.3: Using a metaclass .............................................................................................................................. 162
Section 28.4: Introduction to Metaclasses .............................................................................................................. 162
Section 28.5: Custom functionality with metaclasses ........................................................................................... 163
Section 28.6: The default metaclass ....................................................................................................................... 164
Chapter 29: String Methods ................................................................................................................................ 166
Section 29.1: Changing the capitalization of a string ............................................................................................. 166
Section 29.2: str.translate: Translating characters in a string .............................................................................. 167
Section 29.3: str.format and f-strings: Format values into a string ..................................................................... 167
Section 29.4: String module's useful constants ...................................................................................................... 168
Section 29.5: Stripping unwanted leading/trailing characters from a string ..................................................... 170
Section 29.6: Reversing a string .............................................................................................................................. 170
Section 29.7: Split a string based on a delimiter into a list of strings .................................................................. 171
Section 29.8: Replace all occurrences of one substring with another substring ................................................ 172
Section 29.9: Testing what a string is composed of .............................................................................................. 172
Section 29.10: String Contains .................................................................................................................................. 175
Section 29.11: Join a list of strings into one string .................................................................................................. 175
Section 29.12: Counting number of times a substring appears in a string ......................................................... 175
Section 29.13: Case insensitive string comparisons ............................................................................................... 176
Section 29.14: Justify strings .................................................................................................................................... 177
Section 29.15: Test the starting and ending characters of a string ..................................................................... 177
Section 29.16: Conversion between str or bytes data and unicode characters ................................................. 178
Chapter 30: String Formatting .......................................................................................................................... 180
Section 30.1: Basics of String Formatting ............................................................................................................... 180
Section 30.2: Alignment and padding ..................................................................................................................... 181
Section 30.3: Format literals (f-string) .................................................................................................................... 182
Section 30.4: Float formatting ................................................................................................................................. 182
Section 30.5: Named placeholders .......................................................................................................................... 183
Section 30.6: String formatting with datetime ....................................................................................................... 184
Section 30.7: Formatting Numerical Values ........................................................................................................... 184
Section 30.8: Nested formatting .............................................................................................................................. 185
Section 30.9: Format using Getitem and Getattr ................................................................................................... 185
Section 30.10: Padding and truncating strings, combined .................................................................................... 185
Section 30.11: Custom formatting for a class ......................................................................................................... 186
Chapter 31: Conditionals ....................................................................................................................................... 188
Section 31.1: Conditional Expression (or "The Ternary Operator") ....................................................................... 188
Section 31.2: if, elif, and else ..................................................................................................................................... 188
Section 31.3: Truth Values ......................................................................................................................................... 188
Section 31.4: Boolean Logic Expressions ................................................................................................................. 189
Section 31.5: Using the cmp function to get the comparison result of two objects ........................................... 191
Section 31.6: Else statement ..................................................................................................................................... 191
Section 31.7: Testing if an object is None and assigning it .................................................................................... 191
Section 31.8: If statement .......................................................................................................................................... 192
Chapter 32: Loops .................................................................................................................................................... 193
Section 32.1: Break and Continue in Loops ............................................................................................................. 193
Section 32.2: For loops ............................................................................................................................................. 195
Section 32.3: Iterating over lists ............................................................................................................................... 195
Section 32.4: Loops with an "else" clause ............................................................................................................... 196
Section 32.5: The Pass Statement ........................................................................................................................... 198
Section 32.6: Iterating over dictionaries .................................................................................................................. 199
Section 32.7: The "half loop" do-while ..................................................................................................................... 200
Section 32.8: Looping and Unpacking .................................................................................................................... 200
Section 32.9: Iterating dierent portion of a list with dierent step size ............................................................ 201
Section 32.10: While Loop ......................................................................................................................................... 202
Chapter 33: Using loops within functions ..................................................................................................... 203
Section 33.1: Return statement inside loop in a function ....................................................................................... 203
Chapter 34: Importing modules ........................................................................................................................ 204
Section 34.1: Importing a module ............................................................................................................................ 204
Section 34.2: The __all__ special variable ............................................................................................................ 205
Section 34.3: Import modules from an arbitrary filesystem location .................................................................. 206
Section 34.4: Importing all names from a module ................................................................................................ 206
Section 34.5: Programmatic importing ................................................................................................................... 207
Section 34.6: PEP8 rules for Imports ....................................................................................................................... 207
Section 34.7: Importing specific names from a module ........................................................................................ 208
Section 34.8: Importing submodules ....................................................................................................................... 208
Section 34.9: Re-importing a module ...................................................................................................................... 208
Section 34.10: __import__() function ..................................................................................................................... 209
Chapter 35: Dierence between Module and Package ........................................................................ 210
Section 35.1: Modules ................................................................................................................................................ 210
Section 35.2: Packages ............................................................................................................................................. 210
Chapter 36: Math Module ..................................................................................................................................... 211
Section 36.1: Rounding: round, floor, ceil, trunc ...................................................................................................... 211
Section 36.2: Trigonometry ...................................................................................................................................... 212
Section 36.3: Pow for faster exponentiation ........................................................................................................... 213
Section 36.4: Infinity and NaN ("not a number") ................................................................................................... 213
Section 36.5: Logarithms .......................................................................................................................................... 216
Section 36.6: Constants ............................................................................................................................................. 216
Section 36.7: Imaginary Numbers ........................................................................................................................... 217
Section 36.8: Copying signs ...................................................................................................................................... 217
Section 36.9: Complex numbers and the cmath module ...................................................................................... 217
Chapter 37: Complex math .................................................................................................................................. 220
Section 37.1: Advanced complex arithmetic ........................................................................................................... 220
Section 37.2: Basic complex arithmetic ................................................................................................................... 221
Chapter 38: Collections module ........................................................................................................................ 222
Section 38.1: collections.Counter .............................................................................................................................. 222
Section 38.2: collections.OrderedDict ...................................................................................................................... 223
Section 38.3: collections.defaultdict ......................................................................................................................... 224
Section 38.4: collections.namedtuple ...................................................................................................................... 225
Section 38.5: collections.deque ................................................................................................................................ 226
Section 38.6: collections.ChainMap ......................................................................................................................... 227
Chapter 39: Operator module ............................................................................................................................ 229
Section 39.1: Itemgetter ............................................................................................................................................ 229
Section 39.2: Operators as alternative to an infix operator ................................................................................. 229
Section 39.3: Methodcaller ....................................................................................................................................... 229
Chapter 40: JSON Module ................................................................................................................................... 231
Section 40.1: Storing data in a file ........................................................................................................................... 231
Section 40.2: Retrieving data from a file ................................................................................................................ 231
Section 40.3: Formatting JSON output ................................................................................................................... 231
Section 40.4: `load` vs `loads`, `dump` vs `dumps` .................................................................................................. 232
Section 40.5: Calling `json.tool` from the command line to pretty-print JSON output ...................................... 233
Section 40.6: JSON encoding custom objects ....................................................................................................... 233
Section 40.7: Creating JSON from Python dict ...................................................................................................... 234
Section 40.8: Creating Python dict from JSON ...................................................................................................... 234
Chapter 41: Sqlite3 Module .................................................................................................................................. 235
Section 41.1: Sqlite3 - Not require separate server process .................................................................................. 235
Section 41.2: Getting the values from the database and Error handling ............................................................ 235
Chapter 42: The os Module ................................................................................................................................. 237
Section 42.1: makedirs - recursive directory creation ........................................................................................... 237
Section 42.2: Create a directory .............................................................................................................................. 238
Section 42.3: Get current directory .......................................................................................................................... 238
Section 42.4: Determine the name of the operating system ............................................................................... 238
Section 42.5: Remove a directory ........................................................................................................................... 238
Section 42.6: Follow a symlink (POSIX) ................................................................................................................... 238
Section 42.7: Change permissions on a file ............................................................................................................ 238
Chapter 43: The locale Module ......................................................................................................................... 239
Section 43.1: Currency Formatting US Dollars Using the locale Module ............................................................. 239
Chapter 44: Itertools Module ............................................................................................................................ 240
Section 44.1: Combinations method in Itertools Module ....................................................................................... 240
Section 44.2: itertools.dropwhile .............................................................................................................................. 240
Section 44.3: Zipping two iterators until they are both exhausted ...................................................................... 241
Section 44.4: Take a slice of a generator ............................................................................................................... 241
Section 44.5: Grouping items from an iterable object using a function .............................................................. 242
Section 44.6: itertools.takewhile ............................................................................................................................... 243
Section 44.7: itertools.permutations ........................................................................................................................ 243
Section 44.8: itertools.repeat .................................................................................................................................... 244
Section 44.9: Get an accumulated sum of numbers in an iterable ...................................................................... 244
Section 44.10: Cycle through elements in an iterator ............................................................................................ 244
Section 44.11: itertools.product ................................................................................................................................. 244
Section 44.12: itertools.count .................................................................................................................................... 245
Section 44.13: Chaining multiple iterators together ............................................................................................... 246
Chapter 45: Asyncio Module ............................................................................................................................... 247
Section 45.1: Coroutine and Delegation Syntax ..................................................................................................... 247
Section 45.2: Asynchronous Executors ................................................................................................................... 248
Section 45.3: Using UVLoop ..................................................................................................................................... 249
Section 45.4: Synchronization Primitive: Event ....................................................................................................... 249
Section 45.5: A Simple Websocket .......................................................................................................................... 250
Section 45.6: Common Misconception about asyncio .......................................................................................... 250
Chapter 46: Random module ............................................................................................................................. 252
Section 46.1: Creating a random user password ................................................................................................... 252
Section 46.2: Create cryptographically secure random numbers ....................................................................... 252
Section 46.3: Random and sequences: shue, choice and sample .................................................................... 253
Section 46.4: Creating random integers and floats: randint, randrange, random, and uniform ...................... 254
Section 46.5: Reproducible random numbers: Seed and State ............................................................................ 255
Section 46.6: Random Binary Decision ................................................................................................................... 256
Chapter 47: Functools Module .......................................................................................................................... 257
Section 47.1: partial ................................................................................................................................................... 257
Section 47.2: cmp_to_key ....................................................................................................................................... 257
Section 47.3: lru_cache ............................................................................................................................................. 257
Section 47.4: total_ordering ..................................................................................................................................... 258
Section 47.5: reduce .................................................................................................................................................. 259
Chapter 48: The dis module ............................................................................................................................... 260
Section 48.1: What is Python bytecode? ................................................................................................................. 260
Section 48.2: Constants in the dis module .............................................................................................................. 260
Section 48.3: Disassembling modules ..................................................................................................................... 260
Chapter 49: The base64 Module ...................................................................................................................... 262
Section 49.1: Encoding and Decoding Base64 ....................................................................................................... 263
Section 49.2: Encoding and Decoding Base32 ....................................................................................................... 264
Section 49.3: Encoding and Decoding Base16 ........................................................................................................ 264
Section 49.4: Encoding and Decoding ASCII85 ...................................................................................................... 265
Section 49.5: Encoding and Decoding Base85 ....................................................................................................... 265
Chapter 50: Queue Module .................................................................................................................................. 267
Section 50.1: Simple example ................................................................................................................................... 267
Chapter 51: Deque Module ................................................................................................................................... 268
Section 51.1: Basic deque using ................................................................................................................................ 268
Section 51.2: Available methods in deque ............................................................................................................... 268
Section 51.3: limit deque size .................................................................................................................................... 269
Section 51.4: Breadth First Search ........................................................................................................................... 269
Chapter 52: Usage of "pip" module: PyPI Package Manager ............................................................ 270
Section 52.1: Example use of commands ............................................................................................................... 270
Section 52.2: Handling ImportError Exception ....................................................................................................... 270
Section 52.3: Force install ......................................................................................................................................... 271
Chapter 53: Webbrowser Module ..................................................................................................................... 272
Section 53.1: Opening a URL with Default Browser ............................................................................................... 272
Section 53.2: Opening a URL with Dierent Browsers .......................................................................................... 273
Chapter 54: pyautogui module ......................................................................................................................... 274
Section 54.1: Mouse Functions .................................................................................................................................. 274
Section 54.2: Keyboard Functions ........................................................................................................................... 274
Section 54.3: ScreenShot And Image Recognition ................................................................................................. 274
Chapter 55: Plotting with Matplotlib .............................................................................................................. 275
Section 55.1: Plots with Common X-axis but dierent Y-axis : Using twinx() ....................................................... 275
Section 55.2: Plots with common Y-axis and dierent X-axis using twiny() ....................................................... 276
Section 55.3: A Simple Plot in Matplotlib ................................................................................................................. 278
Section 55.4: Adding more features to a simple plot : axis labels, title, axis ticks, grid, and legend ................ 279
Section 55.5: Making multiple plots in the same figure by superimposition similar to MATLAB ...................... 280
Section 55.6: Making multiple Plots in the same figure using plot superimposition with separate plot
commands ......................................................................................................................................................... 281
Chapter 56: Comparisons ..................................................................................................................................... 283
Section 56.1: Chain Comparisons ............................................................................................................................. 283
Section 56.2: Comparison by `is` vs `==` ................................................................................................................... 284
Section 56.3: Greater than or less than ................................................................................................................... 285
Section 56.4: Not equal to ........................................................................................................................................ 285
Section 56.5: Equal To ............................................................................................................................................... 286
Section 56.6: Comparing Objects ............................................................................................................................ 286
Chapter 57: Sorting, Minimum and Maximum ............................................................................................ 288
Section 57.1: Make custom classes orderable ........................................................................................................ 288
Section 57.2: Special case: dictionaries ................................................................................................................... 290
Section 57.3: Using the key argument .................................................................................................................... 291
Section 57.4: Default Argument to max, min .......................................................................................................... 291
Section 57.5: Getting a sorted sequence ................................................................................................................ 292
Section 57.6: Extracting N largest or N smallest items from an iterable ............................................................ 292
Section 57.7: Getting the minimum or maximum of several values .................................................................... 293
Section 57.8: Minimum and Maximum of a sequence ........................................................................................... 293
Chapter 58: Variable Scope and Binding ..................................................................................................... 294
Section 58.1: Nonlocal Variables .............................................................................................................................. 294
Section 58.2: Global Variables ................................................................................................................................. 294
Section 58.3: Local Variables ................................................................................................................................... 295
Section 58.4: The del command .............................................................................................................................. 296
Section 58.5: Functions skip class scope when looking up names ...................................................................... 297
Section 58.6: Local vs Global Scope ........................................................................................................................ 298
Section 58.7: Binding Occurrence ............................................................................................................................ 300
Chapter 59: Basic Input and Output ............................................................................................................... 301
Section 59.1: Using the print function ...................................................................................................................... 301
Section 59.2: Input from a File ................................................................................................................................. 301
Section 59.3: Read from stdin .................................................................................................................................. 303
Section 59.4: Using input() and raw_input() .......................................................................................................... 303
Section 59.5: Function to prompt user for a number ............................................................................................ 303
Section 59.6: Printing a string without a newline at the end ................................................................................. 304
Chapter 60: Files & Folders I/O ......................................................................................................................... 306
Section 60.1: File modes ............................................................................................................................................ 306
Section 60.2: Reading a file line-by-line ................................................................................................................. 307
Section 60.3: Iterate files (recursively) .................................................................................................................... 308
Section 60.4: Getting the full contents of a file ...................................................................................................... 308
Section 60.5: Writing to a file ................................................................................................................................... 309
Section 60.6: Check whether a file or path exists .................................................................................................. 310
Section 60.7: Random File Access Using mmap .................................................................................................... 311
Section 60.8: Replacing text in a file ....................................................................................................................... 311
Section 60.9: Checking if a file is empty ................................................................................................................. 311
Section 60.10: Read a file between a range of lines .............................................................................................. 312
Section 60.11: Copy a directory tree ........................................................................................................................ 312
Section 60.12: Copying contents of one file to a dierent file .............................................................................. 312
Chapter 61: Indexing and Slicing ....................................................................................................................... 313
Section 61.1: Basic Slicing .......................................................................................................................................... 313
Section 61.2: Reversing an object ............................................................................................................................ 314
Section 61.3: Slice assignment .................................................................................................................................. 314
Section 61.4: Making a shallow copy of an array .................................................................................................. 314
Section 61.5: Indexing custom classes: __getitem__, __setitem__ and __delitem__ .................................... 315
Section 61.6: Basic Indexing ...................................................................................................................................... 316
Chapter 62: Generators ......................................................................................................................................... 317
Section 62.1: Introduction .......................................................................................................................................... 317
Section 62.2: Infinite sequences ............................................................................................................................... 319
Section 62.3: Sending objects to a generator ........................................................................................................ 320
Section 62.4: Yielding all values from another iterable ......................................................................................... 321
Section 62.5: Iteration ............................................................................................................................................... 321
Section 62.6: The next() function ............................................................................................................................. 321
Section 62.7: Coroutines ........................................................................................................................................... 322
Section 62.8: Refactoring list-building code ........................................................................................................... 322
Section 62.9: Yield with recursion: recursively listing all files in a directory ........................................................ 323
Section 62.10: Generator expressions ..................................................................................................................... 324
Section 62.11: Using a generator to find Fibonacci Numbers ............................................................................... 324
Section 62.12: Searching ........................................................................................................................................... 324
Section 62.13: Iterating over generators in parallel ............................................................................................... 325
Chapter 63: Reduce ................................................................................................................................................. 326
Section 63.1: Overview ............................................................................................................................................... 326
Section 63.2: Using reduce ....................................................................................................................................... 326
Section 63.3: Cumulative product ............................................................................................................................ 327
Section 63.4: Non short-circuit variant of any/all .................................................................................................. 327
Chapter 64: Map Function ................................................................................................................................... 328
Section 64.1: Basic use of map, itertools.imap and future_builtins.map ............................................................. 328
Section 64.2: Mapping each value in an iterable ................................................................................................... 328
Section 64.3: Mapping values of dierent iterables .............................................................................................. 329
Section 64.4: Transposing with Map: Using "None" as function argument (python 2.x only) .......................... 331
Section 64.5: Series and Parallel Mapping .............................................................................................................. 331
Chapter 65: Exponentiation ................................................................................................................................. 334
Section 65.1: Exponentiation using builtins: ** and pow() ....................................................................................... 334
Section 65.2: Square root: math.sqrt() and cmath.sqrt ......................................................................................... 334
Section 65.3: Modular exponentiation: pow() with 3 arguments .......................................................................... 335
Section 65.4: Computing large integer roots ......................................................................................................... 335
Section 65.5: Exponentiation using the math module: math.pow() ..................................................................... 336
Section 65.6: Exponential function: math.exp() and cmath.exp() ......................................................................... 337
Section 65.7: Exponential function minus 1: math.expm1() .................................................................................... 337
Section 65.8: Magic methods and exponentiation: builtin, math and cmath ...................................................... 338
Section 65.9: Roots: nth-root with fractional exponents ....................................................................................... 339
Chapter 66: Searching ............................................................................................................................................ 340
Section 66.1: Searching for an element ................................................................................................................... 340
Section 66.2: Searching in custom classes: __contains__ and __iter__ .......................................................... 340
Section 66.3: Getting the index for strings: str.index(), str.rindex() and str.find(), str.rfind() .............................. 341
Section 66.4: Getting the index list and tuples: list.index(), tuple.index() .............................................................. 342
Section 66.5: Searching key(s) for a value in dict .................................................................................................. 342
Section 66.6: Getting the index for sorted sequences: bisect.bisect_left() .......................................................... 343
Section 66.7: Searching nested sequences ............................................................................................................. 343
Chapter 67: Counting .............................................................................................................................................. 345
Section 67.1: Counting all occurence of all items in an iterable: collections.Counter ......................................... 345
Section 67.2: Getting the most common value(-s): collections.Counter.most_common() ................................ 345
Section 67.3: Counting the occurrences of one item in a sequence: list.count() and tuple.count() .................. 345
Section 67.4: Counting the occurrences of a substring in a string: str.count() ................................................... 346
Section 67.5: Counting occurences in numpy array .............................................................................................. 346
Chapter 68: Manipulating XML .......................................................................................................................... 347
Section 68.1: Opening and reading using an ElementTree ................................................................................... 347
Section 68.2: Create and Build XML Documents .................................................................................................... 347
Section 68.3: Modifying an XML File ........................................................................................................................ 348
Section 68.4: Searching the XML with XPath .......................................................................................................... 348
Section 68.5: Opening and reading large XML files using iterparse (incremental parsing) ............................. 349
Chapter 69: Parallel computation .................................................................................................................... 350
Section 69.1: Using the multiprocessing module to parallelise tasks ................................................................... 350
Section 69.2: Using a C-extension to parallelize tasks .......................................................................................... 350
Section 69.3: Using Parent and Children scripts to execute code in parallel ...................................................... 350
Section 69.4: Using PyPar module to parallelize ................................................................................................... 351
Chapter 70: Processes and Threads ............................................................................................................... 352
Section 70.1: Global Interpreter Lock ....................................................................................................................... 352
Section 70.2: Running in Multiple Threads .............................................................................................................. 353
Section 70.3: Running in Multiple Processes ........................................................................................................... 354
Section 70.4: Sharing State Between Threads ....................................................................................................... 354
Section 70.5: Sharing State Between Processes .................................................................................................... 355
Chapter 71: Multithreading .................................................................................................................................. 356
Section 71.1: Basics of multithreading ...................................................................................................................... 356
Section 71.2: Communicating between threads ..................................................................................................... 357
Section 71.3: Creating a worker pool ....................................................................................................................... 358
Section 71.4: Advanced use of multithreads ........................................................................................................... 358
Section 71.5: Stoppable Thread with a while Loop ................................................................................................. 360
Chapter 72: Writing extensions ......................................................................................................................... 361
Section 72.1: Hello World with C Extension ............................................................................................................. 361
Section 72.2: C Extension Using c++ and Boost ..................................................................................................... 361
Section 72.3: Passing an open file to C Extensions ................................................................................................ 363
Chapter 73: Unit Testing ....................................................................................................................................... 364
Section 73.1: Test Setup and Teardown within a unittest.TestCase ..................................................................... 364
Section 73.2: Asserting on Exceptions ..................................................................................................................... 364
Section 73.3: Testing Exceptions .............................................................................................................................. 365
Section 73.4: Choosing Assertions Within Unittests ............................................................................................... 366
Section 73.5: Unit tests with pytest .......................................................................................................................... 367
Section 73.6: Mocking functions with unittest.mock.create_autospec ................................................................ 370
Chapter 74: Regular Expressions (Regex) ................................................................................................... 372
Section 74.1: Matching the beginning of a string ................................................................................................... 372
Section 74.2: Searching ............................................................................................................................................ 373
Section 74.3: Precompiled patterns ......................................................................................................................... 373
Section 74.4: Flags .................................................................................................................................................... 374
Section 74.5: Replacing ............................................................................................................................................. 375
Section 74.6: Find All Non-Overlapping Matches ................................................................................................... 375
Section 74.7: Checking for allowed characters ...................................................................................................... 376
Section 74.8: Splitting a string using regular expressions ..................................................................................... 376
Section 74.9: Grouping .............................................................................................................................................. 376
Section 74.10: Escaping Special Characters ........................................................................................................... 377
Section 74.11: Match an expression only in specific locations ............................................................................... 378
Section 74.12: Iterating over matches using `re.finditer` ........................................................................................ 379
Chapter 75: Incompatibilities moving from Python 2 to Python 3 .................................................. 380
Section 75.1: Integer Division .................................................................................................................................... 380
Section 75.2: Unpacking Iterables ........................................................................................................................... 381
Section 75.3: Strings: Bytes versus Unicode ........................................................................................................... 383
Section 75.4: Print statement vs. Print function ...................................................................................................... 385
Section 75.5: Dierences between range and xrange functions ......................................................................... 386
Section 75.6: Raising and handling Exceptions ...................................................................................................... 387
Section 75.7: Leaked variables in list comprehension ........................................................................................... 389
Section 75.8: True, False and None ......................................................................................................................... 390
Section 75.9: User Input ............................................................................................................................................ 390
Section 75.10: Comparison of dierent types ........................................................................................................ 390
Section 75.11: .next() method on iterators renamed .............................................................................................. 391
Section 75.12: filter(), map() and zip() return iterators instead of sequences .................................................... 392
Section 75.13: Renamed modules ............................................................................................................................ 392
Section 75.14: Removed operators <> and ``, synonymous with != and repr() .................................................... 393
Section 75.15: long vs. int .......................................................................................................................................... 393
Section 75.16: All classes are "new-style classes" in Python 3 .............................................................................. 394
Section 75.17: Reduce is no longer a built-in .......................................................................................................... 395
Section 75.18: Absolute/Relative Imports ............................................................................................................... 395
Section 75.19: map() .................................................................................................................................................. 397
Section 75.20: The round() function tie-breaking and return type ...................................................................... 398
Section 75.21: File I/O ................................................................................................................................................ 399
Section 75.22: cmp function removed in Python 3 ................................................................................................ 399
Section 75.23: Octal Constants ................................................................................................................................ 400
Section 75.24: Return value when writing to a file object ..................................................................................... 400
Section 75.25: exec statement is a function in Python 3 ....................................................................................... 400
Section 75.26: encode/decode to hex no longer available .................................................................................. 401
Section 75.27: Dictionary method changes ............................................................................................................ 401
Section 75.28: Class Boolean Value ........................................................................................................................ 402
Section 75.29: hasattr function bug in Python 2 .................................................................................................... 403
Chapter 76: Virtual environments .................................................................................................................... 404
Section 76.1: Creating and using a virtual environment ........................................................................................ 404
Section 76.2: Specifying specific python version to use in script on Unix/Linux ................................................ 406
Section 76.3: Creating a virtual environment for a dierent version of python ................................................. 406
Section 76.4: Making virtual environments using Anaconda ................................................................................ 406
Section 76.5: Managing multiple virtual enviroments with virtualenvwrapper ................................................... 407
Section 76.6: Installing packages in a virtual environment ................................................................................... 408
Section 76.7: Discovering which virtual environment you are using .................................................................... 409
Section 76.8: Checking if running inside a virtual environment ............................................................................ 410
Section 76.9: Using virtualenv with fish shell .......................................................................................................... 410
Chapter 77: Copying data .................................................................................................................................... 412
Section 77.1: Copy a dictionary ................................................................................................................................ 412
Section 77.2: Performing a shallow copy ............................................................................................................... 412
Section 77.3: Performing a deep copy .................................................................................................................... 412
Section 77.4: Performing a shallow copy of a list .................................................................................................. 412
Section 77.5: Copy a set ........................................................................................................................................... 412
Chapter 78: Context Managers (“with” Statement) ............................................................................... 414
Section 78.1: Introduction to context managers and the with statement ............................................................ 414
Section 78.2: Writing your own context manager ................................................................................................. 414
Section 78.3: Writing your own contextmanager using generator syntax ......................................................... 415
Section 78.4: Multiple context managers ................................................................................................................ 416
Section 78.5: Assigning to a target .......................................................................................................................... 416
Section 78.6: Manage Resources ............................................................................................................................. 417
Chapter 79: Hidden Features ............................................................................................................................. 418
Section 79.1: Operator Overloading ........................................................................................................................ 418
Chapter 80: Unicode and bytes ........................................................................................................................ 419
Section 80.1: Encoding/decoding error handling .................................................................................................. 419
Section 80.2: File I/O ................................................................................................................................................. 419
Section 80.3: Basics ................................................................................................................................................... 420
Chapter 81: The __name__ special variable ............................................................................................ 422
Section 81.1: __name__ == '__main__' ................................................................................................................. 422
Section 81.2: Use in logging ...................................................................................................................................... 422
Section 81.3: function_class_or_module.__name__ ........................................................................................... 422
Chapter 82: Checking Path Existence and Permissions ......................................................................... 424
Section 82.1: Perform checks using os.access ........................................................................................................ 424
Chapter 83: Python Networking ....................................................................................................................... 425
Section 83.1: Creating a Simple Http Server ........................................................................................................... 425
Section 83.2: Creating a TCP server ........................................................................................................................ 425
Section 83.3: Creating a UDP Server ....................................................................................................................... 426
Section 83.4: Start Simple HttpServer in a thread and open the browser .......................................................... 426
Section 83.5: The simplest Python socket client-server example ........................................................................ 427
Chapter 84: The Print Function ......................................................................................................................... 428
Section 84.1: Print basics ........................................................................................................................................... 428
Section 84.2: Print parameters ................................................................................................................................ 429
Chapter 85: os.path ................................................................................................................................................. 431
Section 85.1: Join Paths ............................................................................................................................................ 431
Section 85.2: Path Component Manipulation ......................................................................................................... 431
Section 85.3: Get the parent directory .................................................................................................................... 431
Section 85.4: If the given path exists ....................................................................................................................... 431
Section 85.5: check if the given path is a directory, file, symbolic link, mount point etc ................................... 432
Section 85.6: Absolute Path from Relative Path .................................................................................................... 432
Chapter 86: Creating Python packages ........................................................................................................ 433
Section 86.1: Introduction .......................................................................................................................................... 433
Section 86.2: Uploading to PyPI ............................................................................................................................... 433
Section 86.3: Making package executable ............................................................................................................. 435
Chapter 87: Parsing Command Line arguments ...................................................................................... 437
Section 87.1: Hello world in argparse ...................................................................................................................... 437
Section 87.2: Using command line arguments with argv ..................................................................................... 437
Section 87.3: Setting mutually exclusive arguments with argparse .................................................................... 438
Section 87.4: Basic example with docopt ............................................................................................................... 439
Section 87.5: Custom parser error message with argparse ................................................................................. 439
Section 87.6: Conceptual grouping of arguments with argparse.add_argument_group() ............................. 440
Section 87.7: Advanced example with docopt and docopt_dispatch ................................................................. 441
Chapter 88: HTML Parsing ................................................................................................................................... 443
Section 88.1: Using CSS selectors in BeautifulSoup ............................................................................................... 443
Section 88.2: PyQuery .............................................................................................................................................. 443
Section 88.3: Locate a text after an element in BeautifulSoup ............................................................................ 444
Chapter 89: Subprocess Library ....................................................................................................................... 445
Section 89.1: More flexibility with Popen ................................................................................................................. 445
Section 89.2: Calling External Commands .............................................................................................................. 446
Section 89.3: How to create the command list argument .................................................................................... 446
Chapter 90: setup.py .............................................................................................................................................. 447
Section 90.1: Purpose of setup.py ............................................................................................................................ 447
Section 90.2: Using source control metadata in setup.py .................................................................................... 447
Section 90.3: Adding command line scripts to your python package ................................................................ 448
Section 90.4: Adding installation options ................................................................................................................ 448
Chapter 91: Sockets ................................................................................................................................................. 450
Section 91.1: Raw Sockets on Linux .......................................................................................................................... 450
Section 91.2: Sending data via UDP ......................................................................................................................... 450
Section 91.3: Receiving data via UDP ...................................................................................................................... 451
Section 91.4: Sending data via TCP ......................................................................................................................... 451
Section 91.5: Multi-threaded TCP Socket Server .................................................................................................... 451
Chapter 92: Recursion ............................................................................................................................................ 454
Section 92.1: The What, How, and When of Recursion .......................................................................................... 454
Section 92.2: Tree exploration with recursion ........................................................................................................ 457
Section 92.3: Sum of numbers from 1 to n .............................................................................................................. 458
Section 92.4: Increasing the Maximum Recursion Depth ...................................................................................... 458
Section 92.5: Tail Recursion - Bad Practice ............................................................................................................ 459
Section 92.6: Tail Recursion Optimization Through Stack Introspection ............................................................ 459
Chapter 93: Type Hints .......................................................................................................................................... 461
Section 93.1: Adding types to a function ................................................................................................................. 461
Section 93.2: NamedTuple ....................................................................................................................................... 462
Section 93.3: Generic Types ..................................................................................................................................... 462
Section 93.4: Variables and Attributes .................................................................................................................... 462
Section 93.5: Class Members and Methods ............................................................................................................ 463
Section 93.6: Type hints for keyword arguments .................................................................................................. 463
Chapter 94: pip: PyPI Package Manager ..................................................................................................... 464
Section 94.1: Install Packages .................................................................................................................................. 464
Section 94.2: To list all packages installed using `pip` ........................................................................................... 464
Section 94.3: Upgrade Packages ............................................................................................................................. 464
Section 94.4: Uninstall Packages ............................................................................................................................. 465
Section 94.5: Updating all outdated packages on Linux ...................................................................................... 465
Section 94.6: Updating all outdated packages on Windows ................................................................................ 465
Section 94.7: Create a requirements.txt file of all packages on the system ....................................................... 465
Section 94.8: Using a certain Python version with pip .......................................................................................... 466
Section 94.9: Create a requirements.txt file of packages only in the current virtualenv .................................. 466
Section 94.10: Installing packages not yet on pip as wheels ................................................................................ 467
Chapter 95: Exceptions .......................................................................................................................................... 470
Section 95.1: Catching Exceptions ............................................................................................................................ 470
Section 95.2: Do not catch everything! ................................................................................................................... 470
Section 95.3: Re-raising exceptions ......................................................................................................................... 471
Section 95.4: Catching multiple exceptions ............................................................................................................ 471
Section 95.5: Exception Hierarchy ........................................................................................................................... 472
Section 95.6: Else ....................................................................................................................................................... 474
Section 95.7: Raising Exceptions .............................................................................................................................. 474
Section 95.8: Creating custom exception types ..................................................................................................... 475
Section 95.9: Practical examples of exception handling ....................................................................................... 475
Section 95.10: Exceptions are Objects too .............................................................................................................. 476
Section 95.11: Running clean-up code with finally .................................................................................................. 476
Section 95.12: Chain exceptions with raise from .................................................................................................... 477
Chapter 96: Web scraping with Python ......................................................................................................... 478
Section 96.1: Scraping using the Scrapy framework ............................................................................................. 478
Section 96.2: Scraping using Selenium WebDriver ................................................................................................ 478
Section 96.3: Basic example of using requests and lxml to scrape some data ................................................. 479
Section 96.4: Maintaining web-scraping session with requests ........................................................................... 479
Section 96.5: Scraping using BeautifulSoup4 ......................................................................................................... 480
Section 96.6: Simple web content download with urllib.request .......................................................................... 480
Section 96.7: Modify Scrapy user agent ................................................................................................................. 480
Section 96.8: Scraping with curl ............................................................................................................................... 480
Chapter 97: Distribution ........................................................................................................................................ 482
Section 97.1: py2app ................................................................................................................................................. 482
Section 97.2: cx_Freeze ............................................................................................................................................ 483
Chapter 98: Property Objects ............................................................................................................................ 484
Section 98.1: Using the @property decorator for read-write properties ............................................................ 484
Section 98.2: Using the @property decorator ....................................................................................................... 484
Section 98.3: Overriding just a getter, setter or a deleter of a property object ................................................. 485
Section 98.4: Using properties without decorators ............................................................................................... 485
Chapter 99: Overloading ....................................................................................................................................... 488
Section 99.1: Operator overloading ......................................................................................................................... 488
Section 99.2: Magic/Dunder Methods ..................................................................................................................... 489
Section 99.3: Container and sequence types ......................................................................................................... 490
Section 99.4: Callable types ..................................................................................................................................... 491
Section 99.5: Handling unimplemented behaviour ................................................................................................ 491
Chapter 100: Debugging ....................................................................................................................................... 493
Section 100.1: Via IPython and ipdb ......................................................................................................................... 493
Section 100.2: The Python Debugger: Step-through Debugging with _pdb_ .................................................... 493
Section 100.3: Remote debugger ............................................................................................................................. 495
Chapter 101: Reading and Writing CSV .......................................................................................................... 496
Section 101.1: Using pandas ...................................................................................................................................... 496
Section 101.2: Writing a TSV file ............................................................................................................................... 496
Chapter 102: Dynamic code execution with `exec` and `eval` ............................................................. 497
Section 102.1: Executing code provided by untrusted user using exec, eval, or ast.literal_eval ....................... 497
Section 102.2: Evaluating a string containing a Python literal with ast.literal_eval ........................................... 497
Section 102.3: Evaluating statements with exec ..................................................................................................... 497
Section 102.4: Evaluating an expression with eval ................................................................................................. 498
Section 102.5: Precompiling an expression to evaluate it multiple times ............................................................ 498
Section 102.6: Evaluating an expression with eval using custom globals ........................................................... 498
Chapter 103: PyInstaller - Distributing Python Code .............................................................................. 499
Section 103.1: Installation and Setup ........................................................................................................................ 499
Section 103.2: Using Pyinstaller ................................................................................................................................ 499
Section 103.3: Bundling to One Folder ..................................................................................................................... 500
Section 103.4: Bundling to a Single File ................................................................................................................... 500
Chapter 104: Iterables and Iterators ............................................................................................................. 501
Section 104.1: Iterator vs Iterable vs Generator ...................................................................................................... 501
Section 104.2: Extract values one by one ............................................................................................................... 502
Section 104.3: Iterating over entire iterable ............................................................................................................ 502
Section 104.4: Verify only one element in iterable ................................................................................................. 502
Section 104.5: What can be iterable ........................................................................................................................ 503
Section 104.6: Iterator isn't reentrant! ...................................................................................................................... 503
Chapter 105: Data Visualization with Python ............................................................................................. 504
Section 105.1: Seaborn ............................................................................................................................................... 504
Section 105.2: Matplotlib ........................................................................................................................................... 506
Section 105.3: Plotly ................................................................................................................................................... 507
Section 105.4: MayaVI ............................................................................................................................................... 509
Chapter 106: The Interpreter (Command Line Console) ....................................................................... 511
Section 106.1: Getting general help .......................................................................................................................... 511
Section 106.2: Referring to the last expression ...................................................................................................... 511
Section 106.3: Opening the Python console ............................................................................................................ 512
Section 106.4: The PYTHONSTARTUP variable ...................................................................................................... 512
Section 106.5: Command line arguments ............................................................................................................... 512
Section 106.6: Getting help about an object ........................................................................................................... 513
Chapter 107: *args and **kwargs ...................................................................................................................... 515
Section 107.1: Using **kwargs when writing functions ............................................................................................ 515
Section 107.2: Using *args when writing functions ................................................................................................. 515
Section 107.3: Populating kwarg values with a dictionary .................................................................................... 516
Section 107.4: Keyword-only and Keyword-required arguments ........................................................................ 516
Section 107.5: Using **kwargs when calling functions ........................................................................................... 516
Section 107.6: **kwargs and default values ............................................................................................................ 516
Section 107.7: Using *args when calling functions ................................................................................................. 517
Chapter 108: Garbage Collection ...................................................................................................................... 518
Section 108.1: Reuse of primitive objects ................................................................................................................ 518
Section 108.2: Eects of the del command ............................................................................................................ 518
Section 108.3: Reference Counting .......................................................................................................................... 519
Section 108.4: Garbage Collector for Reference Cycles ....................................................................................... 519
Section 108.5: Forcefully deallocating objects ....................................................................................................... 520
Section 108.6: Viewing the refcount of an object ................................................................................................... 521
Section 108.7: Do not wait for the garbage collection to clean up ...................................................................... 521
Section 108.8: Managing garbage collection ......................................................................................................... 521
Chapter 109: Pickle data serialisation ............................................................................................................ 523
Section 109.1: Using Pickle to serialize and deserialize an object ......................................................................... 523
Section 109.2: Customize Pickled Data ................................................................................................................... 523
Chapter 110: urllib ..................................................................................................................................................... 525
Section 110.1: HTTP GET ............................................................................................................................................ 525
Section 110.2: HTTP POST ......................................................................................................................................... 525
Section 110.3: Decode received bytes according to content type encoding ....................................................... 526
Chapter 111: Binary Data ....................................................................................................................................... 527
Section 111.1: Format a list of values into a byte object ......................................................................................... 527
Section 111.2: Unpack a byte object according to a format string ....................................................................... 527
Section 111.3: Packing a structure ............................................................................................................................. 527
Chapter 112: Python and Excel ........................................................................................................................... 529
Section 112.1: Read the excel data using xlrd module ............................................................................................ 529
Section 112.2: Format Excel files with xlsxwriter ..................................................................................................... 529
Section 112.3: Put list data into a Excel's file ............................................................................................................ 530
Section 112.4: OpenPyXL ........................................................................................................................................... 531
Section 112.5: Create excel charts with xlsxwriter ................................................................................................... 531
Chapter 113: Idioms .................................................................................................................................................. 534
Section 113.1: Dictionary key initializations .............................................................................................................. 534
Section 113.2: Switching variables ............................................................................................................................ 534
Section 113.3: Use truth value testing ....................................................................................................................... 534
Section 113.4: Test for "__main__" to avoid unexpected code execution .......................................................... 535
Chapter 114: Method Overriding ....................................................................................................................... 536
Section 114.1: Basic method overriding .................................................................................................................... 536
Chapter 115: Data Serialization .......................................................................................................................... 537
Section 115.1: Serialization using JSON .................................................................................................................... 537
Section 115.2: Serialization using Pickle ................................................................................................................... 537
Chapter 116: Python concurrency ..................................................................................................................... 539
Section 116.1: The multiprocessing module ............................................................................................................. 539
Section 116.2: The threading module ....................................................................................................................... 540
Section 116.3: Passing data between multiprocessing processes ........................................................................ 540
Chapter 117: Introduction to RabbitMQ using AMQPStorm ................................................................. 542
Section 117.1: How to consume messages from RabbitMQ ................................................................................... 542
Section 117.2: How to publish messages to RabbitMQ .......................................................................................... 543
Section 117.3: How to create a delayed queue in RabbitMQ ................................................................................. 543
Chapter 118: Descriptor .......................................................................................................................................... 546
Section 118.1: Simple descriptor ................................................................................................................................ 546
Section 118.2: Two-way conversions ....................................................................................................................... 547
Chapter 119: Multiprocessing ............................................................................................................................... 548
Section 119.1: Running Two Simple Processes ........................................................................................................ 548
Section 119.2: Using Pool and Map .......................................................................................................................... 548
Chapter 120: tempfile NamedTemporaryFile ............................................................................................ 550
Section 120.1: Create (and write to a) known, persistant temporary file ............................................................. 550
Chapter 121: Input, Subset and Output External Data Files using Pandas .................................. 551
Section 121.1: Basic Code to Import, Subset and Write External Data Files Using Pandas ................................ 551
Chapter 122: Writing to CSV from String or List ....................................................................................... 553
Section 122.1: Basic Write Example .......................................................................................................................... 553
Section 122.2: Appending a String as a newline in a CSV file ............................................................................... 553
Chapter 123: Unzipping Files ................................................................................................................................ 554
Section 123.1: Using Python ZipFile.extractall() to decompress a ZIP file ........................................................... 554
Section 123.2: Using Python TarFile.extractall() to decompress a tarball ........................................................... 554
Chapter 124: Working with ZIP archives ....................................................................................................... 555
Section 124.1: Examining Zipfile Contents ............................................................................................................... 555
Section 124.2: Opening Zip Files .............................................................................................................................. 555
Section 124.3: Extracting zip file contents to a directory ....................................................................................... 556
Section 124.4: Creating new archives ...................................................................................................................... 556
Chapter 125: Stack ................................................................................................................................................... 557
Section 125.1: Creating a Stack class with a List Object ........................................................................................ 557
Section 125.2: Parsing Parentheses ......................................................................................................................... 558
Chapter 126: Profiling ............................................................................................................................................. 559
Section 126.1: %%timeit and %timeit in IPython ...................................................................................................... 559
Section 126.2: Using cProfile (Preferred Profiler) ................................................................................................... 559
Section 126.3: timeit() function ................................................................................................................................. 559
Section 126.4: timeit command line ......................................................................................................................... 560
Section 126.5: line_profiler in command line .......................................................................................................... 560
Chapter 127: User-Defined Methods ............................................................................................................... 561
Section 127.1: Creating user-defined method objects ............................................................................................ 561
Section 127.2: Turtle example ................................................................................................................................... 562
Chapter 128: Working around the Global Interpreter Lock (GIL) ..................................................... 563
Section 128.1: Multiprocessing.Pool .......................................................................................................................... 563
Section 128.2: Cython nogil: ...................................................................................................................................... 564
Chapter 129: Deployment ..................................................................................................................................... 565
Section 129.1: Uploading a Conda Package ........................................................................................................... 565
Chapter 130: Logging .............................................................................................................................................. 567
Section 130.1: Introduction to Python Logging ....................................................................................................... 567
Section 130.2: Logging exceptions ........................................................................................................................... 568
Chapter 131: Database Access ............................................................................................................................ 571
Section 131.1: SQLite ................................................................................................................................................... 571
Section 131.2: Accessing MySQL database using MySQLdb ................................................................................. 576
Section 131.3: Connection .......................................................................................................................................... 577
Section 131.4: PostgreSQL Database access using psycopg2 .............................................................................. 578
Section 131.5: Oracle database ................................................................................................................................ 579
Section 131.6: Using sqlalchemy ............................................................................................................................... 580
Chapter 132: Python HTTP Server .................................................................................................................... 582
Section 132.1: Running a simple HTTP server ......................................................................................................... 582
Section 132.2: Serving files ........................................................................................................................................ 582
Section 132.3: Basic handling of GET, POST, PUT using BaseHTTPRequestHandler ......................................... 583
Section 132.4: Programmatic API of SimpleHTTPServer ....................................................................................... 584
Chapter 133: Web Server Gateway Interface (WSGI) ............................................................................. 586
Section 133.1: Server Object (Method) ..................................................................................................................... 586
Chapter 134: Python Server Sent Events ..................................................................................................... 587
Section 134.1: Flask SSE ............................................................................................................................................. 587
Section 134.2: Asyncio SSE ........................................................................................................................................ 587
Chapter 135: Connecting Python to SQL Server ....................................................................................... 588
Section 135.1: Connect to Server, Create Table, Query Data ................................................................................ 588
Chapter 136: Sockets And Message Encryption/Decryption Between Client and Server
............................................................................................................................................................................................ 589
Section 136.1: Server side Implementation .............................................................................................................. 589
Section 136.2: Client side Implementation ............................................................................................................... 591
Chapter 137: Alternatives to switch statement from other languages ........................................ 593
Section 137.1: Use what the language oers: the if/else construct ...................................................................... 593
Section 137.2: Use a dict of functions ...................................................................................................................... 593
Section 137.3: Use class introspection ..................................................................................................................... 594
Section 137.4: Using a context manager ................................................................................................................. 595
Chapter 138: List Comprehensions ................................................................................................................... 596
Section 138.1: Conditional List Comprehensions ..................................................................................................... 596
Section 138.2: List Comprehensions with Nested Loops ........................................................................................ 597
Section 138.3: Refactoring filter and map to list comprehensions ....................................................................... 598
Section 138.4: Nested List Comprehensions ........................................................................................................... 599
Section 138.5: Iterate two or more list simultaneously within list comprehension .............................................. 600
Chapter 139: List destructuring (aka packing and unpacking) ......................................................... 601
Section 139.1: Destructuring assignment ................................................................................................................. 601
Section 139.2: Packing function arguments ............................................................................................................ 602
Section 139.3: Unpacking function arguments ....................................................................................................... 604
Chapter 140: Accessing Python source code and bytecode .............................................................. 605
Section 140.1: Display the bytecode of a function ................................................................................................. 605
Section 140.2: Display the source code of an object ............................................................................................. 605
Section 140.3: Exploring the code object of a function .......................................................................................... 606
Chapter 141: Mixins ................................................................................................................................................... 607
Section 141.1: Mixin ..................................................................................................................................................... 607
Section 141.2: Overriding Methods in Mixins ............................................................................................................ 608
Chapter 142: Attribute Access ............................................................................................................................ 609
Section 142.1: Basic Attribute Access using the Dot Notation ............................................................................... 609
Section 142.2: Setters, Getters & Properties ............................................................................................................ 609
Chapter 143: ArcPy .................................................................................................................................................. 611
Section 143.1: Printing one field's value for all rows of feature class in file geodatabase using Search
Cursor ................................................................................................................................................................. 611
Section 143.2: createDissolvedGDB to create a file gdb on the workspace ....................................................... 611
Chapter 144: Abstract Base Classes (abc) .................................................................................................. 612
Section 144.1: Setting the ABCMeta metaclass ....................................................................................................... 612
Section 144.2: Why/How to use ABCMeta and @abstractmethod ...................................................................... 612
Chapter 145: Plugin and Extension Classes ................................................................................................. 614
Section 145.1: Mixins ................................................................................................................................................... 614
Section 145.2: Plugins with Customized Classes ..................................................................................................... 615
Chapter 146: Websockets ..................................................................................................................................... 617
Section 146.1: Simple Echo with aiohttp ................................................................................................................... 617
Section 146.2: Wrapper Class with aiohttp .............................................................................................................. 617
Section 146.3: Using Autobahn as a Websocket Factory ...................................................................................... 618
Chapter 147: Immutable datatypes(int, float, str, tuple and frozensets) .................................. 620
Section 147.1: Individual characters of strings are not assignable ....................................................................... 620
Section 147.2: Tuple's individual members aren't assignable ............................................................................... 620
Section 147.3: Frozenset's are immutable and not assignable ............................................................................. 620
Chapter 148: String representations of class instances: __str__ and __repr__
methods ........................................................................................................................................................................ 621
Section 148.1: Motivation ........................................................................................................................................... 621
Section 148.2: Both methods implemented, eval-round-trip style __repr__() .................................................. 625
Chapter 149: Polymorphism ................................................................................................................................ 626
Section 149.1: Duck Typing ....................................................................................................................................... 626
Section 149.2: Basic Polymorphism ......................................................................................................................... 626
Chapter 150: Non-ocial Python implementations ............................................................................... 629
Section 150.1: IronPython .......................................................................................................................................... 629
Section 150.2: Jython ................................................................................................................................................ 629
Section 150.3: Transcrypt ......................................................................................................................................... 630
Chapter 151: 2to3 tool ............................................................................................................................................. 633
Section 151.1: Basic Usage ......................................................................................................................................... 633
Chapter 152: Abstract syntax tree ................................................................................................................... 635
Section 152.1: Analyze functions in a python script ................................................................................................ 635
Chapter 153: Unicode .............................................................................................................................................. 637
Section 153.1: Encoding and decoding .................................................................................................................... 637
Chapter 154: Python Serial Communication (pyserial) ......................................................................... 638
Section 154.1: Initialize serial device ......................................................................................................................... 638
Section 154.2: Read from serial port ....................................................................................................................... 638
Section 154.3: Check what serial ports are available on your machine .............................................................. 638
Chapter 155: Neo4j and Cypher using Py2Neo ......................................................................................... 640
Section 155.1: Adding Nodes to Neo4j Graph .......................................................................................................... 640
Section 155.2: Importing and Authenticating .......................................................................................................... 640
Section 155.3: Adding Relationships to Neo4j Graph ............................................................................................. 640
Section 155.4: Query 1 : Autocomplete on News Titles .......................................................................................... 640
Section 155.5: Query 2 : Get News Articles by Location on a particular date ..................................................... 641
Section 155.6: Cypher Query Samples .................................................................................................................... 641
Chapter 156: Basic Curses with Python .......................................................................................................... 642
Section 156.1: The wrapper() helper function ......................................................................................................... 642
Section 156.2: Basic Invocation Example ................................................................................................................ 642
Chapter 157: Performance optimization ....................................................................................................... 643
Section 157.1: Code profiling ..................................................................................................................................... 643
Chapter 158: Templates in python ................................................................................................................... 645
Section 158.1: Simple data output program using template ................................................................................. 645
Section 158.2: Changing delimiter ............................................................................................................................ 645
Chapter 159: Pillow ................................................................................................................................................... 646
Section 159.1: Read Image File ................................................................................................................................. 646
Section 159.2: Convert files to JPEG ........................................................................................................................ 646
Chapter 160: The pass statement .................................................................................................................... 647
Section 160.1: Ignore an exception ........................................................................................................................... 647
Section 160.2: Create a new Exception that can be caught .................................................................................. 647
Chapter 161: py.test ................................................................................................................................................. 648
Section 161.1: Setting up py.test ................................................................................................................................ 648
Section 161.2: Intro to Test Fixtures .......................................................................................................................... 648
Section 161.3: Failing Tests ........................................................................................................................................ 651
Chapter 162: Heapq ................................................................................................................................................. 653
Section 162.1: Largest and smallest items in a collection ...................................................................................... 653
Section 162.2: Smallest item in a collection ............................................................................................................ 653
Chapter 163: tkinter ................................................................................................................................................. 655
Section 163.1: Geometry Managers .......................................................................................................................... 655
Section 163.2: A minimal tkinter Application ........................................................................................................... 656
Chapter 164: CLI subcommands with precise help output .................................................................. 658
Section 164.1: Native way (no libraries) ................................................................................................................... 658
Section 164.2: argparse (default help formatter) .................................................................................................. 658
Section 164.3: argparse (custom help formatter) .................................................................................................. 659
Chapter 165: PostgreSQL ...................................................................................................................................... 661
Section 165.1: Getting Started ................................................................................................................................... 661
Chapter 166: Python Persistence ...................................................................................................................... 662
Section 166.1: Python Persistence ............................................................................................................................ 662
Section 166.2: Function utility for save and load .................................................................................................... 663
Chapter 167: Turtle Graphics .............................................................................................................................. 664
Section 167.1: Ninja Twist (Turtle Graphics) ............................................................................................................ 664
Chapter 168: Design Patterns ............................................................................................................................. 665
Section 168.1: Introduction to design patterns and Singleton Pattern ................................................................. 665
Section 168.2: Strategy Pattern ................................................................................................................................ 667
Section 168.3: Proxy ................................................................................................................................................... 668
Chapter 169: Multidimensional arrays ........................................................................................................... 670
Section 169.1: Lists in lists .......................................................................................................................................... 670
Section 169.2: Lists in lists in lists in.. ........................................................................................................................ 670
Chapter 170: Audio ................................................................................................................................................... 672
Section 170.1: Working with WAV files ..................................................................................................................... 672
Section 170.2: Convert any soundfile with python and mpeg ............................................................................ 672
Section 170.3: Playing Windows' beeps ................................................................................................................... 672
Section 170.4: Audio With Pyglet .............................................................................................................................. 673
Chapter 171: Pyglet .................................................................................................................................................. 674
Section 171.1: Installation of Pyglet ........................................................................................................................... 674
Section 171.2: Hello World in Pyglet ......................................................................................................................... 674
Section 171.3: Playing Sound in Pyglet ..................................................................................................................... 674
Section 171.4: Using Pyglet for OpenGL ................................................................................................................... 674
Section 171.5: Drawing Points Using Pyglet and OpenGL ...................................................................................... 674
Chapter 172: Flask .................................................................................................................................................... 676
Section 172.1: Files and Templates ........................................................................................................................... 676
Section 172.2: The basics .......................................................................................................................................... 676
Section 172.3: Routing URLs ..................................................................................................................................... 677
Section 172.4: HTTP Methods ................................................................................................................................... 678
Section 172.5: Jinja Templating ............................................................................................................................... 678
Section 172.6: The Request Object ........................................................................................................................... 679
Chapter 173: groupby() .......................................................................................................................................... 681
Section 173.1: Example 4 ............................................................................................................................................ 681
Section 173.2: Example 2 ........................................................................................................................................... 681
Section 173.3: Example 3 ........................................................................................................................................... 682
Chapter 174: pygame ............................................................................................................................................. 684
Section 174.1: Pygame's mixer module .................................................................................................................... 684
Section 174.2: Installing pygame ............................................................................................................................. 685
Chapter 175: hashlib ................................................................................................................................................ 686
Section 175.1: MD5 hash of a string ......................................................................................................................... 686
Section 175.2: algorithm provided by OpenSSL ..................................................................................................... 687
Chapter 176: getting start with GZip .............................................................................................................. 688
Section 176.1: Read and write GNU zip files ............................................................................................................ 688
Chapter 177: ctypes ................................................................................................................................................. 689
Section 177.1: ctypes arrays ...................................................................................................................................... 689
Section 177.2: Wrapping functions for ctypes ........................................................................................................ 689
Section 177.3: Basic usage ........................................................................................................................................ 690
Section 177.4: Common pitfalls ................................................................................................................................ 690
Section 177.5: Basic ctypes object ........................................................................................................................... 691
Section 177.6: Complex usage .................................................................................................................................. 692
Chapter 178: Creating a Windows service using Python ...................................................................... 693
Section 178.1: A Python script that can be run as a service .................................................................................. 693
Section 178.2: Running a Flask web application as a service ............................................................................... 694
Chapter 179: Mutable vs Immutable (and Hashable) in Python ....................................................... 695
Section 179.1: Mutable vs Immutable ....................................................................................................................... 695
Section 179.2: Mutable and Immutable as Arguments .......................................................................................... 697
Chapter 180: Python speed of program ....................................................................................................... 699
Section 180.1: Deque operations .............................................................................................................................. 699
Section 180.2: Algorithmic Notations ....................................................................................................................... 699
Section 180.3: Notation ............................................................................................................................................. 700
Section 180.4: List operations ................................................................................................................................... 701
Section 180.5: Set operations ................................................................................................................................... 701
Chapter 181: configparser .................................................................................................................................... 703
Section 181.1: Creating configuration file programatically .................................................................................... 703
Section 181.2: Basic usage ........................................................................................................................................ 703
Chapter 182: Commonwealth Exceptions ..................................................................................................... 704
Section 182.1: Other Errors ........................................................................................................................................ 704
Section 182.2: NameError: name '???' is not defined ............................................................................................. 705
Section 182.3: TypeErrors ......................................................................................................................................... 706
Section 182.4: Syntax Error on good code .............................................................................................................. 707
Section 182.5: IndentationErrors (or indentation SyntaxErrors) ........................................................................... 708
Chapter 183: Optical Character Recognition .............................................................................................. 710
Section 183.1: PyTesseract ........................................................................................................................................ 710
Section 183.2: PyOCR ................................................................................................................................................ 710
Chapter 184: graph-tool ....................................................................................................................................... 712
Section 184.1: PyDotPlus ............................................................................................................................................ 712
Section 184.2: PyGraphviz ......................................................................................................................................... 712
Chapter 185: Python Virtual Environment - virtualenv ......................................................................... 714
Section 185.1: Installation .......................................................................................................................................... 714
Section 185.2: Usage ................................................................................................................................................. 714
Section 185.3: Install a package in your Virtualenv ............................................................................................... 714
Section 185.4: Other useful virtualenv commands ................................................................................................. 715
Chapter 186: sys ........................................................................................................................................................ 716
Section 186.1: Command line arguments ................................................................................................................ 716
Section 186.2: Script name ........................................................................................................................................ 716
Section 186.3: Standard error stream ...................................................................................................................... 716
Section 186.4: Ending the process prematurely and returning an exit code ...................................................... 716
Chapter 187: virtual environment with virtualenvwrapper ................................................................ 717
Section 187.1: Create virtual environment with virtualenvwrapper ...................................................................... 717
Chapter 188: Create virtual environment with virtualenvwrapper in windows ........................ 719
Section 188.1: Virtual environment with virtualenvwrapper for windows ............................................................ 719
Chapter 189: Python Requests Post ................................................................................................................ 720
Section 189.1: Simple Post ......................................................................................................................................... 720
Section 189.2: Form Encoded Data ......................................................................................................................... 721
Section 189.3: File Upload ......................................................................................................................................... 721
Section 189.4: Responses .......................................................................................................................................... 722
Section 189.5: Authentication ................................................................................................................................... 722
Section 189.6: Proxies ................................................................................................................................................ 723
Chapter 190: Python Lex-Yacc ........................................................................................................................... 725
Section 190.1: Getting Started with PLY ................................................................................................................... 725
Section 190.2: The "Hello, World!" of PLY - A Simple Calculator ........................................................................... 725
Section 190.3: Part 1: Tokenizing Input with Lex ...................................................................................................... 727
Section 190.4: Part 2: Parsing Tokenized Input with Yacc ..................................................................................... 730
Chapter 191: ChemPy - python package ....................................................................................................... 734
Section 191.1: Parsing formulae ................................................................................................................................ 734
Section 191.2: Balancing stoichiometry of a chemical reaction ............................................................................ 734
Section 191.3: Balancing reactions ........................................................................................................................... 734
Section 191.4: Chemical equilibria ............................................................................................................................ 735
Section 191.5: Ionic strength ...................................................................................................................................... 735
Section 191.6: Chemical kinetics (system of ordinary dierential equations) ..................................................... 735
Chapter 192: pyaudio .............................................................................................................................................. 737
Section 192.1: Callback Mode Audio I/O .................................................................................................................. 737
Section 192.2: Blocking Mode Audio I/O ................................................................................................................. 738
Chapter 193: shelve .................................................................................................................................................. 740
Section 193.1: Creating a new Shelf .......................................................................................................................... 740
Section 193.2: Sample code for shelve .................................................................................................................... 741
Section 193.3: To summarize the interface (key is a string, data is an arbitrary object): .................................. 741
Section 193.4: Write-back ......................................................................................................................................... 741
Chapter 194: IoT Programming with Python and Raspberry PI ....................................................... 743
Section 194.1: Example - Temperature sensor ........................................................................................................ 743
Chapter 195: kivy - Cross-platform Python Framework for NUI Development ....................... 746
Section 195.1: First App .............................................................................................................................................. 746
Chapter 196: Call Python from C# .................................................................................................................... 748
Section 196.1: Python script to be called by C# application .................................................................................. 748
Section 196.2: C# code calling Python script .......................................................................................................... 748
Chapter 197: Similarities in syntax, Dierences in meaning: Python vs. JavaScript ............. 750
Section 197.1: `in` with lists ......................................................................................................................................... 750
Chapter 198: Raise Custom Errors / Exceptions ....................................................................................... 751
Section 198.1: Custom Exception .............................................................................................................................. 751
Section 198.2: Catch custom Exception ................................................................................................................... 751
Chapter 199: Pandas Transform: Preform operations on groups and concatenate the
results ............................................................................................................................................................................. 752
Section 199.1: Simple transform ............................................................................................................................... 752
Section 199.2: Multiple results per group ................................................................................................................ 753
Chapter 200: Security and Cryptography ................................................................................................... 754
Section 200.1: Secure Password Hashing ............................................................................................................... 754
Section 200.2: Calculating a Message Digest ........................................................................................................ 754
Section 200.3: Available Hashing Algorithms ......................................................................................................... 754
Section 200.4: File Hashing ...................................................................................................................................... 755
Section 200.5: Generating RSA signatures using pycrypto .................................................................................. 755
Section 200.6: Asymmetric RSA encryption using pycrypto ................................................................................ 756
Section 200.7: Symmetric encryption using pycrypto .......................................................................................... 757
Chapter 201: Secure Shell Connection in Python ...................................................................................... 758
Section 201.1: ssh connection ................................................................................................................................... 758
Chapter 202: Python Anti-Patterns ................................................................................................................. 759
Section 202.1: Overzealous except clause .............................................................................................................. 759
Section 202.2: Looking before you leap with processor-intensive function ....................................................... 759
Chapter 203: Common Pitfalls ........................................................................................................................... 761
Section 203.1: List multiplication and common references ................................................................................... 761
Section 203.2: Mutable default argument .............................................................................................................. 764
Section 203.3: Changing the sequence you are iterating over ............................................................................ 765
Section 203.4: Integer and String identity .............................................................................................................. 768
Section 203.5: Dictionaries are unordered ............................................................................................................. 769
Section 203.6: Variable leaking in list comprehensions and for loops ................................................................ 770
Section 203.7: Chaining of or operator ................................................................................................................... 770
Section 203.8: sys.argv[0] is the name of the file being executed ...................................................................... 771
Section 203.9: Accessing int literals' attributes ...................................................................................................... 771
Section 203.10: Global Interpreter Lock (GIL) and blocking threads ................................................................... 772
Section 203.11: Multiple return .................................................................................................................................. 773
Section 203.12: Pythonic JSON keys ....................................................................................................................... 773
Credits ............................................................................................................................................................................ 775
You may also like ...................................................................................................................................................... 789
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
http://GoalKicker.com/PythonBook
This Python® Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official Python® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
You can download and install either version of Python here. See Python 3 vs. Python 2 for a comparison between
them. In addition, some third-parties offer re-packaged versions of Python that add commonly used libraries and
other features to ease setup for common use cases, such as math, data analysis or scientific use. See the list at the
official site.
To confirm that Python was installed correctly, you can verify that by running the following command in your
favorite terminal (If you are using Windows OS, you need to add path of python to the environment variable before
using it in command prompt):
$ python --version
If you have Python 3 installed, and it is your default version (see Troubleshooting for more details) you should see
$ python --version
Python 3.6.0
If you have Python 2 installed, and it is your default version (see Troubleshooting for more details) you should see
something like this:
$ python --version
Python 2.7.13
If you have installed Python 3, but $ python --version outputs a Python 2 version, you also have Python 2
installed. This is often the case on MacOS, and many Linux distributions. Use $ python3 instead to explicitly use the
Python 3 interpreter.
IDLE is a simple editor for Python, that comes bundled with Python.
>>>
Hit Enter .
print('Hello, World')
You can use the Python 3 print function in Python 2 with the following import statement:
Python 2 has a number of functionalities that can be optionally imported from Python 3 using the __future__
If using Python 2, you may also type the line below. Note that this is not valid in Python 3 and thus not
recommended because it reduces cross-version code compatibility.
$ python hello.py
Hello, World
You can also substitute hello.py with the path to your file. For example, if you have the file in your home directory
and your user is "user" on Linux, you can type python /home/user/hello.py.
By executing (running) the python command in your terminal, you are presented with an interactive Python shell.
This is also known as the Python Interpreter or a REPL (for 'Read Evaluate Print Loop').
$ python
Python 2.7.12 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello, World'
Hello, World
>>>
If you want to run Python 3 from your terminal, execute the command python3.
$ python3
Python 3.6.0 (default, Jan 13 2017, 00:00:00)
[GCC 6.1.1 20160602] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello, World')
Hello, World
>>>
Alternatively, start the interactive prompt and load file with python -i <file.py>.
$ python -i hello.py
"Hello World"
>>>
>>> exit()
>>> quit()
Alternatively, CTRL + D will close the shell and put you back on your terminal's command line.
If you want to cancel a command you're in the middle of typing and get back to a clean command prompt, while
staying inside the Interpreter shell, use CTRL + C .
Run a small code snippet from a machine which lacks python installation(smartphones, tablets etc).
Learn or teach basic Python.
Solve online judge problems.
Examples:
Disclaimer: documentation author(s) are not affiliated with any resources listed below.
https://www.python.org/shell/ - The online Python shell hosted by the official Python website.
https://ideone.com/ - Widely used on the Net to illustrate code snippet behavior.
https://repl.it/languages/python3 - Powerful and simple online compiler, IDE and interpreter. Code, compile,
and run code in Python.
https://www.tutorialspoint.com/execute_python_online.php - Full-featured UNIX shell, and a user-friendly
project explorer.
http://rextester.com/l/python3_online_compiler - Simple and easy to use IDE which shows execution time
This can be useful when concatenating the results of scripts together in the shell.
Package Management - The PyPA recommended tool for installing Python packages is PIP. To install, on your
command line execute pip install <the package name>. For instance, pip install numpy. (Note: On windows
you must add pip to your PATH environment variables. To avoid this, use python -m pip install <the package
name>)
Shells - So far, we have discussed different ways to run code using Python's native interactive shell. Shells use
Python's interpretive power for experimenting with code real-time. Alternative shells include IDLE - a pre-bundled
GUI, IPython - known for extending the interactive experience, etc.
Programs - For long-term storage you can save content to .py files and edit/execute them as scripts or programs
Python tutor allows you to step through Python code so you can visualize how the program will flow, and helps you
to understand where your program went wrong.
PEP8 defines guidelines for formatting Python code. Formatting code well is important so you can quickly read what
the code does.
Python uses = to assign values to variables. There's no need to declare a variable in advance (or to assign a data
type to it), assigning a value to a variable itself declares and initializes the variable with that value. There's no way to
declare a variable without assigning it an initial value.
# Integer
a = 2
print(a)
# Output: 2
# Integer
b = 9223372036854775807
print(b)
# Output: 9223372036854775807
# Floating point
pi = 3.14
print(pi)
# Output: 3.14
# String
c = 'A'
print(c)
# Output: A
# String
name = 'John Doe'
print(name)
# Output: John Doe
# Boolean
q = True
print(q)
# Output: True
Variable assignment works from left to right. So the following will give you an syntax error.
0 = x
=> Output: SyntaxError: can't assign to literal
import keyword
print(keyword.kwlist)
x = True # valid
_y = True # valid
2. The remainder of your variable name may consist of letters, numbers and underscores.
x = 9
y = X*5
=>NameError: name 'X' is not defined
Even though there's no need to specify a data type when declaring a variable in Python, while allocating the
necessary area in memory for the variable, the Python interpreter automatically picks the most suitable built-in
type for it:
a = 2
print(type(a))
# Output: <type 'int'>
b = 9223372036854775807
print(type(b))
# Output: <type 'int'>
pi = 3.14
print(type(pi))
# Output: <type 'float'>
c = 'A'
print(type(c))
# Output: <type 'str'>
q = True
print(type(q))
# Output: <type 'bool'>
x = None
print(type(x))
Now you know the basics of assignment, let's get this subtlety about assignment in python out of the way.
When you use = to do an assignment operation, what's on the left of = is a name for the object on the right. Finally,
what = does is assign the reference of the object on the right to the name on the left.
That is:
a_name = an_object # "a_name" is now a name for the reference to the object "an_object"
So, from many assignment examples above, if we pick pi = 3.14, then pi is a name (not the name, since an object
can have multiple names) for the object 3.14. If you don't understand something below, come back to this point
and read this again! Also, you can take a look at this for a better understanding.
You can assign multiple values to multiple variables in one line. Note that there must be the same number of
arguments on the right and left sides of the = operator:
a, b, c = 1, 2, 3
print(a, b, c)
# Output: 1 2 3
a, b, c = 1, 2
=> Traceback (most recent call last):
=> File "name.py", line N, in <module>
=> a, b, c = 1, 2
=> ValueError: need more than 2 values to unpack
a, b = 1, 2, 3
=> Traceback (most recent call last):
=> File "name.py", line N, in <module>
=> a, b = 1, 2, 3
=> ValueError: too many values to unpack
The error in last example can be obviated by assigning remaining values to equal number of arbitrary variables.
This dummy variable can have any name, but it is conventional to use the underscore (_) for assigning unwanted
values:
a, b, _ = 1, 2, 3
print(a, b)
# Output: 1, 2
Note that the number of _ and number of remaining values must be equal. Otherwise 'too many values to unpack
error' is thrown as above:
a, b, _ = 1,2,3,4
=>Traceback (most recent call last):
=>File "name.py", line N, in <module>
=>a, b, _ = 1,2,3,4
=>ValueError: too many values to unpack (expected 3)
a = b = c = 1
print(a, b, c)
# Output: 1 1 1
a = b = c = 1 # all three names a, b and c refer to same int object with value 1
print(a, b, c)
# Output: 1 1 1
b = 2 # b now refers to another int object, one with a value of 2
print(a, b, c)
# Output: 1 2 1 # so output is as expected.
The above is also true for mutable types (like list, dict, etc.) just as it is true for immutable types (like int, string,
tuple, etc.):
x = y = [7, 8, 9] # x and y refer to the same list object just created, [7, 8, 9]
x = [13, 8, 9] # x now refers to a different list object just created, [13, 8, 9]
print(y) # y still refers to the list it was first assigned
# Output: [7, 8, 9]
So far so good. Things are a bit different when it comes to modifying the object (in contrast to assigning the name to
a different object, which we did above) when the cascading assignment is used for mutable types. Take a look
below, and you will see it first hand:
x = y = [7, 8, 9] # x and y are two different names for the same list object just created, [7,
8, 9]
x[0] = 13 # we are updating the value of the list [7, 8, 9] through one of its names, x
in this case
print(y) # printing the value of the list using its other name
# Output: [13, 8, 9] # hence, naturally the change is reflected
Nested lists are also valid in python. This means that a list can contain another list as an element.
Lastly, variables in Python do not have to stay the same type as which they were first defined -- you can simply use
= to assign a new value to a variable, even if that value is of a different type.
a = 2
print(a)
# Output: 2
a = "New value"
print(a)
# Output: New value
If this bothers you, think about the fact that what's on the left of = is just a name for an object. First you call the int
object with value 2 a, then you change your mind and decide to give the name a to a string object, having value
'New value'. Simple, right?
Python uses the colon symbol (:) and indentation for showing where blocks of code begin and end (If you come
from another language, do not confuse this with somehow being related to the ternary operator). That is, blocks in
Python, such as functions, loops, if clauses and other constructs, have no ending identifiers. All blocks start with a
colon and then contain the indented lines below it.
For example:
or
Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not
considered good style:
if a > b: print(a)
else: print(b)
Attempting to do this with more than a single statement will not work:
if x > y: y = x
print(y) # IndentationError: unexpected indent
An empty block causes an IndentationError. Use pass (a command that does nothing) when you have a block with
no content:
def will_be_implemented_later():
pass
Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are preferred.
Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time error is
generated: Inconsistent use of tabs and spaces in indentation and the program will not run.
Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes
the previous indentation to be a multiple of 8 spaces. Since it is common that editors are configured to show tabs
Citing PEP 8:
When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code
that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are
highly recommended!
Many editors have "tabs to spaces" configuration. When configuring the editor, one should differentiate between
the tab character ('\t') and the Tab key.
The tab character should be configured to show 8 spaces, to match the language semantics - at least in cases
when (accidental) mixed indentation is possible. Editors can also automatically convert the tab character to
spaces.
However, it might be helpful to configure the editor so that pressing the Tab key will insert 4 spaces,
instead of inserting a tab character.
Python source code written with a mix of tabs and spaces, or with non-standard number of indentation spaces can
be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python installations:
reindent.py)
bool: A boolean value of either True or False. Logical operations like and, or, not can be performed on booleans.
In Python 2.x and in Python 3.x, a boolean is also an int. The bool type is a subclass of the int type and True and
False are its only instances:
If boolean values are used in arithmetic operations, their integer values (1 and 0 for True and False) will be used to
return an integer result:
True + False == 1 # 1 + 0 == 1
True * True == 1 # 1 * 1 == 1
Numbers
a = 2
b = 100
c = 123456789
Note: in older versions of Python, a long type was available and this was distinct from int. The two have
been unified.
float: Floating point number; precision depends on the implementation and system architecture, for
CPython the float datatype corresponds to a C double.
a = 2.0
b = 100.e0
c = 123456789.e1
a = 2 + 1j
b = 100 + 10j
The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.
Strings
Python 3.x Version ≥ 3.0
Python differentiates between ordered sequences and unordered collections (such as set and dict).
a = reversed('hello')
a = (1, 2, 3)
b = ('a', 1, 'python', (1, 2))
b[2] = 'something else' # returns a TypeError
a = [1, 2, 3]
a = {1, 2, 'a'}
a = {1: 'one',
2: 'two'}
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which
compare equality must have the same hash value.
Built-in constants
In conjunction with the built-in datatypes there are a small number of built-in constants in the built-in namespace:
a = None # No value will be assigned. Any valid datatype can be assigned later
None doesn't have any natural ordering. Using ordering comparison operators (<, <=, >=, >) isn't supported anymore
and will raise a TypeError.
None is always less than any number (None < -32 evaluates to True).
In python, we can check the datatype of an object using the built-in function type.
a = '123'
print(type(a))
# Out: <class 'str'>
b = 123
print(type(b))
In conditional statements it is possible to test the datatype with isinstance. However, it is usually not encouraged
to rely on the type of the variable.
i = 7
if isinstance(i, int):
i += 1
elif isinstance(i, str):
i = int(i)
i += 1
For information on the differences between type() and isinstance() read: Differences between isinstance and
type in Python
x = None
if x is None:
print('Not a surprise, I just defined x as None.')
For example, '123' is of str type and it can be converted to integer using int function.
a = '123'
b = int(a)
Converting from a float string such as '123.456' can be done using float function.
a = '123.456'
b = float(a)
c = int(a) # ValueError: invalid literal for int() with base 10: '123.456'
d = int(b) # 123
a = 'hello'
list(a) # ['h', 'e', 'l', 'l', 'o']
set(a) # {'o', 'e', 'l', 'h'}
tuple(a) # ('h', 'e', 'l', 'l', 'o')
With one letter labels just in front of the quotes you can tell what type of string you want to define.
An object is called mutable if it can be changed. For example, when you pass a list to some function, the list can be
changed:
def f(m):
m.append(3) # adds a number to the list. This is a mutation.
x = [1, 2]
f(x)
x == [1, 2] # False now, since an item was added to the list
An object is called immutable if it cannot be changed in any way. For example, integers are immutable, since there's
no way to change them:
def bar():
x = (1, 2)
g(x)
x == (1, 2) # Will always be True, since no function can change the object (1, 2)
Note that variables themselves are mutable, so we can reassign the variable x, but this does not change the object
that x had previously pointed to. It only made x point to a new object.
Data types whose instances are mutable are called mutable data types, and similarly for immutable objects and
datatypes.
bytearray
list
set
dict
Lists
The list type is probably the most commonly used collection type in Python. Despite its name, a list is more like an
array in other languages, mostly JavaScript. In Python, a list is merely an ordered collection of valid Python values. A
list can be created by enclosing values, separated by commas, in square brackets:
int_list = [1, 2, 3]
string_list = ['abc', 'defghi']
empty_list = []
The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic
language:
The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are
zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on:
Indices can also be negative which means counting from the end of the list (-1 being the index of the last element).
So, using the list from the above example:
print(names[-1]) # Eric
print(names[-4]) # Bob
names[0] = 'Ann'
print(names)
# Outputs ['Ann', 'Bob', 'Craig', 'Diana', 'Eric']
names.insert(1, "Nikki")
print(names)
# Outputs ['Alice', 'Nikki', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia']
names.remove("Bob")
print(names) # Outputs ['Alice', 'Nikki', 'Craig', 'Diana', 'Eric', 'Sia']
Get the index in the list of the first item whose value is x. It will show an error if there is no such item.
name.index("Alice")
len(names)
6
a = [1, 1, 1, 2, 3, 4]
a.count(1)
3
a.reverse()
[4, 3, 2, 1, 1, 1]
# or
a[::-1]
[4, 3, 2, 1, 1, 1]
Remove and return item at index (defaults to the last item) with L.pop([index]), returns the item
Tuples
A tuple is similar to a list except that it is fixed-length and immutable. So the values in the tuple cannot be changed
nor the values be added to or removed from the tuple. Tuples are commonly used for small collections of values
that will not need to change, such as an IP address and port. Tuples are represented with parentheses instead of
square brackets:
The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can be any valid
Python valid.
A tuple with only one member must be defined (note the comma) this way:
or
Dictionaries
state_capitals = {
'Arkansas': 'Little Rock',
'Colorado': 'Denver',
'California': 'Sacramento',
'Georgia': 'Atlanta'
}
ca_capital = state_capitals['California']
You can also get all of the keys in a dictionary and then iterate over them:
for k in state_capitals.keys():
print('{} is the capital of {}'.format(state_capitals[k], k))
Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library can be used to
convert between JSON and dictionaries.
set
A set is a collection of elements with no repeats and without insertion order but sorted order. They are used in
situations where it is only important that some things are grouped together, and not what order they were
included. For large groups of data, it is much faster to check whether or not an element is in a set than it is to do
the same for a list.
my_list = [1,2,3]
my_set = set(my_list)
if name in first_names:
print(name)
You can iterate over a set exactly like a list, but remember: the values will be in a arbitrary, implementation-defined
order.
defaultdict
A defaultdict is a dictionary with a default value for keys, so that keys for which no value has been explicitly
defined can be accessed without errors. defaultdict is especially useful when the values in the dictionary are
collections (lists, dicts, etc) in the sense that it does not need to be initialized every time when a new key is used.
A defaultdict will never raise a KeyError. Any key that does not exist gets the default value returned.
>>> state_capitals['Alabama']
Traceback (most recent call last):
KeyError: 'Alabama'
What we did here is to set a default value (Boston) in case the give key does not exist. Now populate the dict as
before:
If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston
>>> state_capitals['Alabama']
'Boston'
and returns the created values for existing key just like a normal dictionary
>>> state_capitals['Arkansas']
'Little Rock'
Multi-window text editor with syntax highlighting, autocompletion, and smart indent
Python shell with syntax highlighting
Integrated debugger with stepping, persistent breakpoints, and call stack visibility
Automatic indentation (useful for beginners learning about Python's indentation)
Saving the Python program as .py files and run them and edit them later at any them using IDLE.
In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE can be a better learning experience for
Note that there are lots of alternatives, see for example this discussion or this list.
Troubleshooting
Windows
If you're on Windows, the default command is python. If you receive a "'python' is not recognized" error,
the most likely cause is that Python's location is not in your system's PATH environment variable. This can be
accessed by right-clicking on 'My Computer' and selecting 'Properties' or by navigating to 'System' through
'Control Panel'. Click on 'Advanced system settings' and then 'Environment Variables...'. Edit the PATH variable
to include the directory of your Python installation, as well as the Script folder (usually
C:\Python27;C:\Python27\Scripts). This requires administrative privileges and may require a restart.
When using multiple versions of Python on the same machine, a possible solution is to rename one of the
python.exe files. For example, naming one version python27.exe would cause python27 to become the
Python command for that version.
You can also use the Python Launcher for Windows, which is available through the installer and comes by
default. It allows you to select the version of Python to run by using py -[x.y] instead of python[x.y]. You
can use the latest version of Python 2 by running scripts with py -2 and the latest version of Python 3 by
running scripts with py -3.
Debian/Ubuntu/MacOS
This section assumes that the location of the python executable has been added to the PATH environment
variable.
If you're on Debian/Ubuntu/MacOS, open the terminal and type python for Python 2.x or python3 for Python
3.x.
Arch Linux
The default Python on Arch Linux (and descendants) is Python 3, so use python or python3 for Python 3.x and
python2 for Python 2.x.
Other systems
Python 3 is sometimes bound to python instead of python3. To use Python 2 on these systems where it is
installed, you can use python2.
Security Remark Do not use input() in Python2 - the entered text will be evaluated as if it were a
Python expression (equivalent to eval(input()) in Python3), which might easily become a vulnerability.
See this article for further information on the risks of using this function.
The function takes a string argument, which displays it as a prompt and returns a string. The above code provides a
prompt, waiting for the user to input.
If the user types "Bob" and hits enter, the variable name will be assigned to the string "Bob":
Note that the input is always of type str, which is important if you want the user to enter numbers. Therefore, you
need to convert the str before trying to use it as a number:
x = input("Write a number:")
# Out: Write a number: 10
x / 2
# Out: TypeError: unsupported operand type(s) for /: 'str' and 'int'
float(x) / 2
# Out: 5.0
NB: It's recommended to use try/except blocks to catch exceptions when dealing with user inputs. For instance, if
your code wants to cast a raw_input into an int, and what the user writes is uncastable, it raises a ValueError.
>>> pow(2,3) #8
To check the built in function in python we can use dir(). If called without an argument, return the names in the
current scope. Else, return an alphabetized list of names comprising (some of) the attribute of the given object, and
of attributes reachable from it.
To know the functionality of any function, we can use built in function help .
>>> help(max)
Help on built-in function max in module __builtin__:
max(...)
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
Built in modules contains extra functionalities.For example to get square root of a number we need to include math
module.
To know all the functions in a module we can assign the functions list to a variable, and then print the variable.
>>> math.__doc__
'This module is always available. It provides access to the\nmathematical
functions defined by the C standard.'
In addition to functions, documentation can also be provided in modules. So, if you have a file named
def sayHello():
"""This is the function docstring."""
return 'Hello World'
For any user defined type, its attributes, its class's attributes, and recursively the attributes of its class's base
classes can be retrieved using dir()
Any data type can be simply converted to string using a builtin function called str. This function is called by default
when a data type is passed to print
# hello.py
def say_hello():
print("Hello!")
For modules that you have made, they will need to be in the same directory as the file that you are importing them
into. (However, you can also put them into the Python lib directory with the pre-included modules, but should be
avoided if possible.)
$ python
>>> import hello
>>> hello.say_hello()
=> "Hello!"
# greet.py
import hello
# greet.py
from hello import say_hello
say_hello()
# greet.py
import hello as ai
ai.say_hello()
# run_hello.py
if __name__ == '__main__':
from hello import say_hello
say_hello()
Run it!
$ python run_hello.py
=> "Hello!"
If the module is inside a directory and needs to be detected by python, the directory should contain a file named
__init__.py.
Note: Following instructions are written for Python 2.7 (unless specified): instructions for Python 3.x are
similar.
WINDOWS
First, download the latest version of Python 2.7 from the official Website (https://www.python.org/downloads/).
Version is provided as an MSI package. To install it manually, just double-click the file.
C:\Python27\
Warning: installation does not automatically modify the PATH environment variable.
Assuming that your Python installation is in C:\Python27, add this to your PATH:
C:\Python27\;C:\Python27\Scripts\
python --version
To install and use both Python 2.x and 3.x side-by-side on a Windows machine:
Python 3 will install the Python launcher which can be used to launch Python 2.x and Python 3.x interchangeably
from the command-line:
P:\>py -3
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
C:\>py -2
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
To use the corresponding version of pip for a specific Python version, use:
C:\>py -3 -m pip -V
pip 9.0.1 from C:\Python36\lib\site-packages (python 3.6)
C:\>py -2 -m pip -V
pip 9.0.1 from C:\Python27\lib\site-packages (python 2.7)
LINUX
The latest versions of CentOS, Fedora, Redhat Enterprise (RHEL) and Ubuntu come with Python 2.7.
Also add the path of new python in PATH environment variable. If new python is in /root/python-2.7.X then run
export PATH = $PATH:/root/python-2.7.X
If you need Python 3.6 you can install it from source as shown below (Ubuntu 16.10 and 17.04 have 3.6 version in
the universal repository). Below steps have to be followed for Ubuntu 16.04 and lower versions:
macOS
As we speak, macOS comes installed with Python 2.7.10, but this version is outdated and slightly modified from the
regular Python.
The version of Python that ships with OS X is great for learning but it’s not good for development. The
version shipped with OS X may be out of date from the official current Python release, which is
considered the stable production version. (source)
Install Homebrew:
For Python 3.x, use the command brew install python3 instead.
repr(x) calls x.__repr__(): a representation of x. eval will usually convert the result of this function back to the
original object.
str(x) calls x.__str__(): a human-readable string that describes the object. This may elide some technical detail.
repr()
For many types, this function makes an attempt to return a string that would yield an object with the same value
when passed to eval(). Otherwise, the representation is a string enclosed in angle brackets that contains the name
of the type of the object along with additional information. This often includes the name and address of the object.
str()
For strings, this returns the string itself. The difference between this and repr(object) is that str(object) does
not always attempt to return a string that is acceptable to eval(). Rather, its goal is to return a printable or 'human
Example 1:
s = """w'o"w"""
repr(s) # Output: '\'w\\\'o"w\''
str(s) # Output: 'w\'o"w'
eval(str(s)) == s # Gives a SyntaxError
eval(repr(s)) == s # Output: True
Example 2:
import datetime
today = datetime.datetime.now()
str(today) # Output: '2016-09-15 06:58:46.915000'
repr(today) # Output: 'datetime.datetime(2016, 9, 15, 6, 58, 46, 915000)'
When writing a class, you can override these methods to do whatever you want:
class Represent(object):
def __repr__(self):
return "Represent(x={},y=\"{}\")".format(self.x, self.y)
def __str__(self):
return "Representing x as {} and y as {}".format(self.x, self.y)
r = Represent(1, "Hopper")
print(r) # prints __str__
print(r.__repr__) # prints __repr__: '<bound method Represent.__repr__ of
Represent(x=1,y="Hopper")>'
rep = r.__repr__() # sets the execution of __repr__ to a new variable
print(rep) # prints 'Represent(x=1,y="Hopper")'
r2 = eval(rep) # evaluates rep
print(r2) # prints __str__ from new object
print(r2 == r) # prints 'False' because they are different objects
On instances with both Python 2 and Python 3 installed, pip often refers to Python 2 and pip3 to Python 3. Using
pip will only install packages for Python 2 and pip3 will only install packages for Python 3.
Installing a package is as simple as typing (in a terminal / command-prompt, not in the Python interpreter)
where x.x.x is the version number of the package you want to install.
When your server is behind proxy, you can install package by using below command:
When new versions of installed packages appear they are not automatically installed to your system. To get an
overview of which of your installed packages have become outdated, run:
Upgrading pip
You can upgrade your existing pip installation by using the following commands
On Linux or macOS X:
You may need to use sudo with pip on some Linux Systems
On Windows:
or
>>> help(help)
help> help
class _Helper(builtins.object)
| Define the builtin 'help'.
|
| This is a wrapper around pydoc.help that provides a helpful message
| when 'help' is typed at the Python interactive prompt.
|
| Calling help() at the Python prompt starts an interactive help session.
| Calling help(thing) prints help for the python object 'thing'.
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
|
| __repr__(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
help(pymysql.connections)
You can use help to access the docstrings of the different modules you have imported, e.g., try the following:
>>> help(math)
And now you will get a list of the available methods in the module, but only AFTER you have imported it.
1. Sets - They are mutable and new elements can be added once sets are defined
2. Frozen Sets - They are immutable and new elements cannot added after its defined.
b = frozenset('asdfagsa')
print(b)
> frozenset({'f', 'g', 'd', 'a', 's'})
cities = frozenset(["Frankfurt", "Basel","Freiburg"])
print(cities)
> frozenset({'Frankfurt', 'Basel', 'Freiburg'})
list = [123,'abcd',10.2,'d'] #can be a array of any data type or single data type.
list1 = ['hello','world']
print(list) #will ouput whole list. [123,'abcd',10.2,'d']
print(list[0:2]) #will output first two element of list. [123,'abcd']
print(list1 * 2) #will gave list1 two times. ['hello','world','hello','world']
print(list + list1) #will gave concatenation of both the lists.
[123,'abcd',10.2,'d','hello','world']
dic={'name':'red','age':10}
print(dic) #will output all the key-value pairs. {'name':'red','age':10}
print(dic['name']) #will output only value with 'name' key. 'red'
print(dic.values()) #will output list of values in dic. ['red',10]
print(dic.keys()) #will output list of keys. ['name','age']
tuple = (123,'hello')
tuple1 = ('world')
print(tuple) #will output whole tuple. (123,'hello')
print(tuple[0]) #will output first value. (123)
print(tuple + tuple1) #will output (123,'hello','world')
tuple[1]='update' #this will give you error.
class ExampleClass:
#Every function belonging to a class must be indented equally
def __init__(self):
name = "example"
#If a function is not indented to the same level it will not be considers as part of the parent class
def separateFunction(b):
for i in b:
#Loops are also indented and nested conditions start a new indentation
if i == 1:
return True
return False
separateFunction([2,3,5,6,1])
Spaces or Tabs?
The recommended indentation is 4 spaces but tabs or spaces can be used so long as they are consistent. Do not
mix tabs and spaces in Python as this will cause an error in Python 3 and can causes errors in Python 2.
The lexical analyzer uses a stack to store indentation levels. At the beginning, the stack contains just the value 0,
which is the leftmost position. Whenever a nested block begins, the new indentation level is pushed on the stack,
and an "INDENT" token is inserted into the token stream which is passed to the parser. There can never be more
than one "INDENT" token in a row (IndentationError).
When a line is encountered with a smaller indentation level, values are popped from the stack until a value is on top
which is equal to the new indentation level (if none is found, a syntax error occurs). For each value popped, a
"DEDENT" token is generated. Obviously, there can be multiple "DEDENT" tokens in a row.
The lexical analyzer skips empty lines (those containing only whitespace and possibly comments), and will never
generate either "INDENT" or "DEDENT" tokens for them.
At the end of the source code, "DEDENT" tokens are generated for each indentation level left on the stack, until just
the 0 is left.
For example:
is analyzed as:
The parser than handles the "INDENT" and "DEDENT" tokens as block delimiters.
a = 7
if a > 5:
print "foo"
else:
print "bar"
print "done"
Or if the line following a colon is not indented, an IndentationError will also be raised:
if True:
print "true"
if True:
a = 6
b = 5
If you forget to un-indent functionality could be lost. In this example None is returned instead of the expected False:
def isEven(a):
if a%2 ==0:
return True
#this next line should be even with the if
return False
print isEven(7)
Python ignores comments, and so will not execute code in there, or raise syntax errors for plain english sentences.
Single-line comments begin with the hash character (#) and are terminated by the end of line.
Inline comment:
Comments spanning multiple lines have """ or ''' on either end. This is the same as a multiline string, but
they can be used as comments:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""
An example function
def func():
"""This is a function that does nothing at all"""
return
print(func.__doc__)
help(func)
func()
help(greet)
greet(name, greeting='Hello')
Just putting no docstring or a regular comment in a function makes it a lot less helpful.
print(greet.__doc__)
None
help(greet)
greet(name, greeting='Hello')
def hello(name):
"""Greet someone.
Print a greeting ("Hello") for the person with the given name.
"""
print("Hello "+name)
class Greeter:
"""An object used to greet people.
The value of the docstring can be accessed within the program and is - for example - used by the help command.
Syntax conventions
PEP 257
PEP 257 defines a syntax standard for docstring comments. It basically allows two types:
One-line Docstrings:
According to PEP 257, they should be used with short and simple functions. Everything is placed in one line, e.g:
def hello():
"""Say hello to your friends."""
print("Hello my friends!")
The docstring shall end with a period, the verb should be in the imperative form.
Multi-line Docstrings:
Multi-line docstring should be used for longer, more complex functions, modules or classes.
Arguments:
name: the name of the person
language: the language in which the person should be greeted
"""
print(greeting[language]+" "+name)
They start with a short summary (equivalent to the content of a one-line docstring) which can be on the same line
as the quotation marks or on the next line, give additional detail and list parameters and return values.
Note PEP 257 defines what information should be given within a docstring, it doesn't define in which format it
should be given. This was the reason for other parties and documentation parsing tools to specify their own
standards for documentation, some of which are listed below and in this question.
Sphinx
Sphinx is a tool to generate HTML based documentation for Python projects based on docstrings. Its markup
language used is reStructuredText. They define their own standards for documentation, pythonhosted.org hosts a
very good description of them. The Sphinx format is for example used by the pyCharm IDE.
print(greeting[language]+" "+name)
return 4
Google has published Google Python Style Guide which defines coding conventions for Python, including
documentation comments. In comparison to the Sphinx/reST many people say that documentation according to
Google's guidelines is better human-readable.
The pythonhosted.org page mentioned above also provides some examples for good documentation according to
the Google Style Guide.
Using the Napoleon plugin, Sphinx can also parse documentation in the Google Style Guide-compliant format.
A function would be documented like this using the Google Style Guide format:
Args:
name: the name of the person as string
language: the language code string
Returns:
A number.
"""
print(greeting[language]+" "+name)
return 4
UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).
import datetime
dt = datetime.datetime.strptime("2016-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")
For other versions of Python, you can use an external library such as dateutil, which makes parsing a string with
timezone into a datetime object is quick.
import dateutil.parser
dt = dateutil.parser.parse("2016-04-15T08:27:18-0500")
For time zones that are a fixed offset from UTC, in Python 3.2+, the datetime module provides the timezone class, a
concrete implementation of tzinfo, which takes a timedelta and an (optional) name parameter:
print(dt.tzname())
# UTC+09:00
For Python versions before 3.2, it is necessary to use a third party library, such as dateutil. dateutil provides an
equivalent class, tzoffset, which (as of version 2.5.3) takes arguments of the form dateutil.tz.tzoffset(tzname,
offset), where offset is specified in seconds:
For zones with daylight savings time, python standard libraries do not provide a standard class, so it is necessary to
use a third party library. pytz and dateutil are popular libraries providing time zone classes.
In addition to static time zones, dateutil provides time zone classes that use daylight savings time (see the
documentation for the tz module). You can use the tz.gettz() method to get a time zone object, which can then
be passed directly to the datetime constructor:
CAUTION: As of version 2.5.3, dateutil does not handle ambiguous datetimes correctly, and will always default to
the later date. There is no way to construct an object with a dateutil timezone representing, for example
2015-11-01 1:30 EDT-4, since this is during a daylight savings time transition.
All edge cases are handled properly when using pytz, but pytz time zones should not be directly attached to time
zones through the constructor. Instead, a pytz time zone should be attached using the time zone's localize
method:
PT = pytz.timezone('US/Pacific')
dt_pst = PT.localize(datetime(2015, 1, 1, 12))
dt_pdt = PT.localize(datetime(2015, 11, 1, 0, 30))
print(dt_pst)
# 2015-01-01 12:00:00-08:00
print(dt_pdt)
# 2015-11-01 00:30:00-07:00
Be aware that if you perform datetime arithmetic on a pytz-aware time zone, you must either perform the
calculations in UTC (if you want absolute elapsed time), or you must call normalize() on the result:
delta = now-then
print(delta.days)
# 60
print(delta.seconds)
# 40826
import datetime
# Date object
today = datetime.date.today()
new_year = datetime.date(2017, 01, 01) #datetime.date(2017, 1, 1)
# Time object
noon = datetime.time(12, 0, 0) #datetime.time(12, 0)
# Current datetime
now = datetime.datetime.now()
Arithmetic operations for these objects are only supported within same datatype and performing simple arithmetic
with instances of different types will result in a TypeError.
# Do this instead
print('Time since the millenium at midnight: ',
datetime.datetime(today.year, today.month, today.day) - millenium_turn)
# Or this
print('Time since the millenium at noon: ',
datetime.datetime.combine(today, noon) - millenium_turn)
utc = tz.tzutc()
local = tz.tzlocal()
utc_now = datetime.utcnow()
utc_now # Not timezone-aware.
utc_now = utc_now.replace(tzinfo=utc)
utc_now # Timezone-aware.
local_now = utc_now.astimezone(local)
local_now # Converted to local time.
import datetime
today = datetime.date.today()
print('Today:', today)
Today: 2016-04-15
Yesterday: 2016-04-14
Tomorrow: 2016-04-16
Difference between tomorrow and yesterday: 2 days, 0:00:00
import time
from datetime import datetime
seconds_since_epoch=time.time() #1469182681.709
import calendar
from datetime import date
import datetime
import dateutil.relativedelta
d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
d2 = d - dateutil.relativedelta.relativedelta(months=1) #datetime.datetime(2013, 2, 28, 0, 0)
But these 2 forms need a different format for strptime. Furthermore, strptime' does not support at all
parsing minute timezones that have a:in it, thus2016-07-22 09:25:59+0300can be parsed, but the
standard format2016-07-22 09:25:59+03:00` cannot.
There is a single-file library called iso8601 which properly parses ISO 8601 timestamps and only them.
It supports fractions and timezones, and the T separator all with a single function:
import iso8601
iso8601.parse_date('2016-07-22 09:25:59')
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)
iso8601.parse_date('2016-07-22 09:25:59+03:00')
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<FixedOffset '+03:00' ...>)
iso8601.parse_date('2016-07-22 09:25:59Z')
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)
iso8601.parse_date('2016-07-22T09:25:59.000111+03:00')
# datetime.datetime(2016, 7, 22, 9, 25, 59, 111, tzinfo=<FixedOffset '+03:00' ...>)
If no timezone is set, iso8601.parse_date defaults to UTC. The default zone can be changed with default_zone
keyword argument. Notably, if this is None instead of the default, then those timestamps that do not have an
explicit timezone are returned as naive datetimes instead:
iso8601.parse_date('2016-07-22T09:25:59', default_timezone=None)
# datetime.datetime(2016, 7, 22, 9, 25, 59)
iso8601.parse_date('2016-07-22T09:25:59Z', default_timezone=None)
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)
datetime.now().isoformat()
# Out: '2016-07-31T23:08:20.886783'
datetime.now(tzlocal()).isoformat()
# Out: '2016-07-31T23:09:43.535074-07:00'
datetime.now(tzlocal()).replace(microsecond=0).isoformat()
# Out: '2016-07-31T23:10:30-07:00'
See ISO 8601 for more information about the ISO 8601 format.
Section 5.11: Parsing a string with a short time zone name into
a timezone aware datetime object
Using the dateutil library as in the previous example on parsing timezone-aware timestamps, it is also possible to
For dates formatted with short time zone names or abbreviations, which are generally ambiguous (e.g. CST, which
could be Central Standard Time, China Standard Time, Cuba Standard Time, etc - more can be found here) or not
necessarily available in a standard database, it is necessary to specify a mapping between time zone abbreviation
and tzinfo object.
ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')
dt_est
# datetime.datetime(2014, 1, 2, 4, 0, tzinfo=tzfile('/usr/share/zoneinfo/US/Eastern'))
dt_pst
# datetime.datetime(2016, 3, 11, 16, 0, tzinfo=tzfile('/usr/share/zoneinfo/US/Pacific'))
It is worth noting that if using a pytz time zone with this method, it will not be properly localized:
EST = pytz.timezone('America/New_York')
dt = parse('2014-02-03 09:17:00 EST', tzinfos={'EST': EST})
If using this method, you should probably re-localize the naive portion of the datetime after parsing:
dt_fixed = dt.tzinfo.localize(dt.replace(tzinfo=None))
dt_fixed.tzinfo # Now it's EST.
# <DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)
dt is now a datetime object and you would see datetime.datetime(2047, 1, 1, 8, 21) printed.
import datetime
start_date = datetime.date.today()
end_date = start_date + 7*day_delta
Which produces:
2016-07-21
2016-07-22
2016-07-23
2016-07-24
2016-07-25
2016-07-26
2016-07-27
a = datetime(2016,10,06,0,0,0)
b = datetime(2016,10,01,23,59,59)
a-b
# datetime.timedelta(4, 1)
(a-b).days
# 4
(a-b).total_seconds()
# 518399.0
class Color(Enum):
red = 1
green = 2
blue = 3
print(Color.red) # Color.red
print(Color(1)) # Color.red
print(Color['red']) # Color.red
class Color(Enum):
red = 1
green = 2
blue = 3
# Intersection
{1, 2, 3, 4, 5}.intersection({3, 4, 5, 6}) # {3, 4, 5}
{1, 2, 3, 4, 5} & {3, 4, 5, 6} # {3, 4, 5}
# Union
{1, 2, 3, 4, 5}.union({3, 4, 5, 6}) # {1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5} | {3, 4, 5, 6} # {1, 2, 3, 4, 5, 6}
# Difference
{1, 2, 3, 4}.difference({2, 3, 5}) # {1, 4}
{1, 2, 3, 4} - {2, 3, 5} # {1, 4}
# Superset check
{1, 2}.issuperset({1, 2, 3}) # False
{1, 2} >= {1, 2, 3} # False
# Subset check
{1, 2}.issubset({1, 2, 3}) # True
{1, 2} <= {1, 2, 3} # True
# Disjoint check
{1, 2}.isdisjoint({3, 4}) # True
{1, 2}.isdisjoint({1, 4}) # False
# Existence check
2 in {1,2,3} # True
4 in {1,2,3} # False
4 not in {1,2,3} # True
s.discard(3) # s == {1,2,4}
s.discard(5) # s == {1,2,4}
s.remove(2) # s == {1,4}
s.remove(2) # KeyError!
Set operations return new sets, but have the corresponding in-place versions:
s = {1, 2}
s.update({3, 4}) # s == {1, 2, 3, 4}
Note that the set is not in the same order as the original list; that is because sets are unordered, just like dicts.
This can easily be transformed back into a List with Python's built in list function, giving another list that is the
same list as the original but without duplicates:
list(unique_restaurants)
# ['Chicken Chicken', "McDonald's", 'Burger King']
Now any operations that could be performed on the original list can be done again.
leads to:
>>> a = {1, 2, 2, 3, 4}
>>> b = {3, 3, 4, 4, 5}
NOTE: {1} creates a set of one element, but {} creates an empty dict. The correct way to create an
empty set is set().
>>> a.intersection(b)
{3, 4}
Union
>>> a.union(b)
{1, 2, 3, 4, 5}
Difference
>>> a.difference(b)
{1, 2}
>>> b.difference(a)
{5}
Symmetric Difference
a.symmetric_difference(b) returns a new set with elements present in either a or b but not in both
>>> a.symmetric_difference(b)
{1, 2, 5}
>>> b.symmetric_difference(a)
{1, 2, 5}
>>> c = {1, 2}
>>> c.issubset(a)
True
>>> a.issuperset(c)
True
Method Operator
a.intersection(b) a & b
a.union(b) a|b
a.difference(b) a - b
a.symmetric_difference(b) a ^ b
a.issubset(b) a <= b
a.issuperset(b) a >= b
Disjoint sets
Testing membership
>>> 1 in a
True
>>> 6 in a
False
Length
The builtin len() function returns the number of elements in the set
>>> len(a)
4
>>> len(b)
3
By saving the strings 'a', 'b', 'b', 'c' into a set data structure we've lost the information on the fact that 'b'
occurs twice. Of course saving the elements to a list would retain this information
but a list data structure introduces an extra unneeded ordering that will slow down our computations.
For implementing multisets Python provides the Counter class from the collections module (starting from version
2.7):
Counter is a dictionary where where elements are stored as dictionary keys and their counts are stored as
dictionary values. And as all dictionaries, it is an unordered collection.
a, b, c, d, e = 3, 2, 2.0, -3, 10
In Python 2 the result of the ' / ' operator depends on the type of the numerator and denominator.
a / b # = 1
a / c # = 1.5
d / b # = -2
b / a # = 0
d / e # = -1
Note that because both a and b are ints, the result is an int.
Recommended:
from __future__ import division # applies Python 3 style division to the entire module
a / b # = 1.5
a // b # = 1
a / (b * 1.0) # = 1.5
1.0 * a / b # = 1.5
a / b * 1.0 # = 1.0 (careful with order of operations)
float(a) / b # = 1.5
a / float(b) # = 1.5
The ' // ' operator in Python 2 forces floored division regardless of type.
a // b # = 1
a // c # = 1.0
In Python 3 the / operator performs 'true' division regardless of types. The // operator performs floor division and
maintains type.
a / b # = 1.5
e / b # = 5.0
a // b # = 1
a // c # = 1.0
Note: the + operator is also used for concatenating strings, lists and tuples:
(a ** b) # = 8
pow(a, b) # = 8
import math
math.pow(a, b) # = 8.0 (always float; does not allow complex results)
import operator
operator.pow(a, b) # = 8
Another difference between the built-in pow and math.pow is that the built-in pow can accept three arguments:
a, b, c = 2, 3, 2
Special functions
import math
import cmath
c = 4
math.sqrt(c) # = 2.0 (always float; does not allow complex results)
cmath.sqrt(c) # = (2+0j) (always complex)
To compute other roots, such as a cube root, raise the number to the reciprocal of the degree of the root. This
could be done with any of the exponential functions or operator.
import math
x = 8
math.pow(x, 1/3) # evaluates to 2.0
x**(1/3) # evaluates to 2.0
math.exp(0) # 1.0
math.exp(1) # 2.718281828459045 (e)
The function math.expm1(x) computes e ** x - 1. When x is small, this gives significantly better precision than
math.exp(x) - 1.
math.exp(1e-6) - 1 # 1.0000004999621837e-06
math.expm1(1e-6) # 1.0000005000001665e-06
# exact result # 1.000000500000166666708333341666...
import math
Note that math.hypot(x, y) is also the length of the vector (or Euclidean distance) from the origin (0, 0)
to the point (x, y).
To compute the Euclidean distance between two points (x1, y1) & (x2, y2) you can use math.hypot as
follows
math.hypot(x2-x1, y2-y1)
To convert from radians -> degrees and degrees -> radians respectively use math.degrees and math.radians
math.degrees(a)
# Out: 57.29577951308232
math.radians(57.29577951308232)
# Out: 1.0
a = a + 1
or
a = a * 2
a += 1
# and
a *= 2
Other in place operators exist for the bitwise operators (^, | etc)
a * b # = 6
import operator
operator.mul(a, b) # = 6
Note: The * operator is also used for repeated concatenation of strings, lists, and tuples:
3 * 'ab' # = 'ababab'
3 * ('a', 'b') # = ('a', 'b', 'a', 'b', 'a', 'b')
import math
import cmath
math.log(5) # = 1.6094379124341003
# optional base argument. Default is math.e
math.log(5, math.e) # = 1.6094379124341003
cmath.log(5) # = (1.6094379124341003+0j)
math.log(1000, 10) # 3.0 (always returns float)
cmath.log(1000, 10) # (3+0j)
# Logarithm base 2
math.log2(8) # = 3.0
# Logarithm base 10
math.log10(100) # = 2.0
cmath.log10(100) # = (2+0j)
3 % 4 # 3
10 % 2 # 0
6 % 4 # 2
import operator
operator.mod(3 , 4) # 3
operator.mod(10 , 2) # 0
operator.mod(6 , 4) # 2
-9 % 7 # 5
9 % -7 # -5
-9 % -7 # -2
If you need to find the result of integer division and modulus, you can use the divmod function as a shortcut:
This means that if you were using 8 bits to represent your two's-complement numbers, you would treat patterns
from 0000 0000 to 0111 1111 to represent numbers from 0 to 127 and reserve 1xxx xxxx to represent negative
numbers.
In essence, this means that whereas 1010 0110 has an unsigned value of 166 (arrived at by adding (128 * 1) +
(64 * 0) + (32 * 1) + (16 * 0) + (8 * 0) + (4 * 1) + (2 * 1) + (1 * 0)), it has a two's-complement value
of -90 (arrived at by adding (128 * 1) - (64 * 0) - (32 * 1) - (16 * 0) - (8 * 0) - (4 * 1) - (2 * 1) -
(1 * 0), and complementing the value).
In this way, negative numbers range down to -128 (1000 0000). Zero (0) is represented as 0000 0000, and minus
one (-1) as 1111 1111.
# 0 = 0b0000 0000
~0
# Out: -1
# -1 = 0b1111 1111
# 1 = 0b0000 0001
~1
# Out: -2
# -2 = 1111 1110
# 2 = 0b0000 0010
~2
# Out: -3
# -3 = 0b1111 1101
Note, the overall effect of this operation when applied to positive numbers can be summarized:
~n -> -|n+1|
And then, when applied to negative numbers, the corresponding effect is:
# -0 = 0b0000 0000
~-0
# Out: -1
# -1 = 0b1111 1111
# 0 is the obvious exception to this rule, as -0 == 0 always
# -1 = 0b1000 0001
~-1
# Out: 0
# 0 = 0b0000 0000
# -2 = 0b1111 1110
~-2
# Out: 1
# 1 = 0b0000 0001
# 0 ^ 0 = 0
# 0 ^ 1 = 1
# 1 ^ 0 = 1
# 1 ^ 1 = 0
# 60 = 0b111100
# 30 = 0b011110
60 ^ 30
# Out: 34
# 34 = 0b100010
bin(60 ^ 30)
# Out: 0b100010
# 0 & 0 = 0
# 0 & 1 = 0
# 1 & 0 = 0
# 1 & 1 = 1
# 60 = 0b111100
# 30 = 0b011110
60 & 30
# Out: 28
# 28 = 0b11100
# 0 | 0 = 0
# 0 | 1 = 1
# 1 | 0 = 1
# 1 | 1 = 1
# 60 = 0b111100
# 30 = 0b011110
60 | 30
# Out: 62
# 62 = 0b111110
bin(60 | 30)
# Out: 0b111110
# 2 = 0b10
2 << 2
# Out: 8
# 8 = 0b1000
bin(2 << 2)
# Out: 0b1000
7 << 1
# Out: 14
3 << 4
# 8 = 0b1000
8 >> 2
# Out: 2
# 2 = 0b10
bin(8 >> 2)
# Out: 0b10
36 >> 1
# Out: 18
15 >> 1
# Out: 7
48 >> 4
# Out: 3
59 >> 3
# Out: 7
a = 0b001
a &= 0b010
# a = 0b000
a = 0b001
a |= 0b010
# a = 0b011
a = 0b001
a <<= 2
# a = 0b100
a = 0b100
a >>= 2
# a = 0b001
a = 0b101
a ^= 0b011
# a = 0b110
For and, it will return its first value if it's false, else it returns the last value:
In many (most?) programming languages, this would be evaluated in a way contrary to regular math: (3.14 < x) <
3.142, but in Python it is treated like 3.14 < x and x < 3.142, just like most non-programmers would expect.
x = True
y = True
z = x and y # z = True
x = True
y = False
z = x and y # z = False
x = False
y = True
z = x and y # z = False
x = False
y = False
z = x and y # z = False
x = 1
y = 1
z = x and y # z = y, so z = 1, see `and` and `or` are not guaranteed to be a boolean
x = 0
y = 1
z = x and y # z = x, so z = 0 (see above)
x = 1
y = 0
z = x and y # z = y, so z = 0 (see above)
x = 0
y = 0
z = x and y # z = x, so z = 0 (see above)
The 1's in the above example can be changed to any truthy value, and the 0's can be changed to any falsey value.
Section 11.5: or
Evaluates to the first truthy argument if either one of the arguments is truthy. If both arguments are falsey,
evaluates to the second argument.
x = True
y = True
z = x or y # z = True
x = True
y = False
z = x or y # z = True
x = False
y = True
z = x or y # z = True
x = 1
y = 1
z = x or y # z = x, so z = 1, see `and` and `or` are not guaranteed to be a boolean
x = 1
y = 0
z = x or y # z = x, so z = 1 (see above)
x = 0
y = 1
z = x or y # z = y, so z = 1 (see above)
x = 0
y = 0
z = x or y # z = y, so z = 0 (see above)
The 1's in the above example can be changed to any truthy value, and the 0's can be changed to any falsey value.
x = True
y = not x # y = False
x = False
y = not x # y = True
Below is a list of operators by precedence, and a brief description of what they (usually) do.
Example:
>>> a, b, c, d = 2, 3, 5, 7
>>> a ** (b + c) # parentheses
256
>>> a * b ** c # exponent: same as `a * (b ** c)`
7776
>>> a + b * c / d # multiplication / division: same as `a + (b * c / d)`
4.142857142857142
def long_name(name):
return len(name) > 5
filter(long_name, names)
# Out: ['Barney']
# Besides the options for older python 2.x versions there is a future_builtin function:
from future_builtins import filter
filter(long_name, names) # identical to itertools.ifilter
# Out: <itertools.ifilter at 0x3eb0ba8>
The next-function gives the next (in this case first) element of and is therefore the reason why it's short-circuit.
# not recommended in real use but keeps the example valid for python 2.x and python 3.x
from itertools import ifilterfalse as filterfalse
which works exactly like the generator filter but keeps only the elements that are False:
def long_name(name):
return len(name) > 5
list(filterfalse(long_name, names))
# Out: ['Fred', 'Wilma']
While python lists can contain values corresponding to different data types, arrays in python can only contain
values corresponding to same data type. In this tutorial, we will understand the Python arrays with few examples.
If you are new to Python, get started with the Python Introduction article.
To use arrays in python language, you need to import the standard array module. This is because array is not a
fundamental data type like strings, integer etc. Here is how you can import array module in python :
Once you have imported the array module, you can declare an array. Here is how you do it:
In the declaration above, arrayIdentifierName is the name of array, typecode lets python know the type of array
and Initializers are the values with which array is initialized.
my_array = array('i',[1,2,3,4])
In the example above, typecode used is i. This typecode represents signed integer whose size is 2 bytes.
Note that the value 6 was appended to the existing array values.
In the above example, the value 0 was inserted at index 0. Note that the first argument is the index while second
argument is the value.
We see that the array my_array was extended with values from my_extnd_array.
Section 14.6: Add items from list into array using fromlist()
So we see that the values 11,12 and 13 were added from list c to my_array.
So we see that the last element (5) was popped out of array.
Section 14.9: Fetch any element through its index using index()
method
index() returns first index of the matching value. Remember that arrays are zero-indexed.
Note in that second example that only one index was returned, even though the value exists twice in the array
creating a dict
literal syntax
d = {} # empty dict
d = {'key': 'value'} # dict with initial values
# Also unpacking one or multiple dictionaries with the literal syntax is possible
dict comprehension
d = {k:v for k,v in [('key', 'value',)]}
modifying a dict
d['newkey'] = 42
d['new_list'] = [1, 2, 3]
d['new_dict'] = {'nested_dict': 1}
del d['newkey']
mydict = {}
mydict['not there']
One way to avoid key errors is to use the dict.get method, which allows you to specify a default value to return in
the case of an absent key.
Which returns mydict[key] if it exists, but otherwise returns default_value. Note that this doesn't add key to
mydict. So if you want to retain that key value pair, you should use mydict.setdefault(key, default_value),
which does store the key value pair.
mydict = {}
print(mydict)
# {}
print(mydict.get("foo", "bar"))
# bar
print(mydict)
# {}
print(mydict.setdefault("foo", "bar"))
# bar
print(mydict)
# {'foo': 'bar'}
try:
value = mydict[key]
except KeyError:
value = default_value
if key in mydict:
value = mydict[key]
else:
value = default_value
Do note, however, that in multi-threaded environments it is possible for the key to be removed from the dictionary
after you check, creating a race condition where the exception can still be thrown.
Another option is to use a subclass of dict, collections.defaultdict, that has a default_factory to create new entries in
the dict when given a new_key.
The items() method can be used to loop over both the key and value simultaneously:
While the values() method can be used to iterate over only the values, as would be expected:
Here, the methods keys(), values() and items() return lists, and there are the three extra methods iterkeys()
itervalues() and iteritems() to return iteraters.
d = defaultdict(int)
d['key'] # 0
d['key'] = 5
d['key'] # 5
d = defaultdict(lambda: 'empty')
d['key'] # 'empty'
d['key'] = 'full'
d['key'] # 'full'
[*] Alternatively, if you must use the built-in dict class, using dict.setdefault() will allow you to create a default
whenever you access a key that did not exist before:
>>> d = {}
{}
>>> d.setdefault('Another_key', []).append("This worked!")
>>> d
Keep in mind that if you have many values to add, dict.setdefault() will create a new instance of the initial value
(in this example a []) every time it's called - which may create unnecessary workloads.
[*] Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly). Copyright 2013 David Beazley and Brian
Jones, 978-1-449-34037-7.
Python 3.5+
>>> fishdog = {**fish, **dog}
>>> fishdog
{'hands': 'paws', 'color': 'red', 'name': 'Clifford', 'special': 'gills'}
As this example demonstrates, duplicate keys map to their lattermost value (for example "Clifford" overrides
"Nemo").
Python 3.3+
>>> from collections import ChainMap
>>> dict(ChainMap(fish, dog))
{'hands': 'fins', 'color': 'red', 'special': 'gills', 'name': 'Nemo'}
With this technique the foremost value takes precedence for a given key rather than the last ("Clifford" is thrown
out in favor of "Nemo").
This uses the lattermost value, as with the **-based technique for merging ("Clifford" overrides "Nemo").
>>> fish.update(dog)
>>> fish
{'color': 'red', 'hands': 'paws', 'name': 'Clifford', 'special': 'gills'}
mydict = {
'a': '1',
'b': '2'
}
print(mydict.keys())
# Python2: ['a', 'b']
# Python3: dict_keys(['b', 'a'])
print(mydict.values())
# Python2: ['1', '2']
# Python3: dict_values(['2', '1'])
If you want to work with both the key and its corresponding value, you can use the items() method:
print(mydict.items())
# Python2: [('a', '1'), ('b', '2')]
# Python3: dict_items([('b', '2'), ('a', '1')])
NOTE: Because a dict is unsorted, keys(), values(), and items() have no sort order. Use sort(), sorted(), or an
OrderedDict if you care about the order that these methods return.
Python 2/3 Difference: In Python 3, these methods return special iterable objects, not lists, and are the equivalent
of the Python 2 iterkeys(), itervalues(), and iteritems() methods. These objects can be used like lists for the
most part, though there are some differences. See PEP 3106 for more details.
The string "Hello" in this example is called a key. It is used to lookup a value in the dict by placing the key in
square brackets.
The number 1234 is seen after the respective colon in the dict definition. This is called the value that "Hello" maps
to in this dict.
Looking up a value like this with a key that does not exist will raise a KeyError exception, halting execution if
uncaught. If we want to access a value without risking a KeyError, we can use the dictionary.get method. By
default if the key does not exist, the method will return None. We can pass it a second value to return instead of
None in the event of a failed lookup.
w = dictionary.get("whatever")
x = dictionary.get("whatever", "nuh-uh")
In this example w will get the value None and x will get the value "nuh-uh".
Use OrderedDict from the collections module. This will always return the dictionary elements in the original
insertion order when iterated over.
d = OrderedDict()
d['first'] = 1
d['second'] = 2
d['third'] = 3
d['last'] = 4
>>>
>>> def parrot(voltage, state, action):
... print("This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
As of Python 3.5 you can also use this syntax to merge an arbitrary number of dict objects.
As this example demonstrates, duplicate keys map to their lattermost value (for example "Clifford" overrides
"Nemo").
PEP 8 dictates that you should leave a space between the trailing comma and the closing brace.
car = {}
car["wheels"] = 4
car["color"] = "Red"
car["model"] = "Corvette"
# wheels: 4
# color: Red
# model: Corvette
Given a dictionary such as the one shown above, where there is a list representing a set of values to explore for the
corresponding key. Suppose you want to explore "x"="a" with "y"=10, then "x"="a" with"y"=10, and so on until
you have explored all possible combinations.
You can create a list that returns all such combinations of values using the following code.
import itertools
options = {
"x": ["a", "b"],
"y": [10, 20, 30]}
keys = options.keys()
values = (options[key] for key in keys)
combinations = [dict(zip(keys, combination)) for combination in itertools.product(*values)]
print combinations
a = [1, 2, 3, 4, 5]
# Append an element of a different type, as list elements do not need to have the same type
my_string = "hello world"
a.append(my_string)
# a: [1, 2, 3, 4, 5, 6, 7, 7, [8, 9], "hello world"]
Note that the append() method only appends one new element to the end of the list. If you append a list to
another list, the list that you append becomes a single element at the end of the first list.
a = [1, 2, 3, 4, 5, 6, 7, 7]
b = [8, 9, 10]
Lists can also be concatenated with the + operator. Note that this does not modify any of the original lists:
3. index(value, [startIndex]) – gets the index of the first occurrence of the input value. If the input value is
not in the list a ValueError exception is raised. If a second argument is provided, the search is started at that
specified index.
a.index(7)
# Returns: 6
a.index(7, 7)
# Returns: 7
4. insert(index, value) – inserts value just before the specified index. Thus after the insertion the new
element occupies position index.
5. pop([index]) – removes and returns the item at index. With no argument it removes and returns the last
element of the list.
a.pop(2)
# Returns: 5
# a: [0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10]
a.pop(8)
# Returns: 7
# a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# With no argument:
a.pop()
# Returns: 10
# a: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6. remove(value) – removes the first occurrence of the specified value. If the provided value cannot be found, a
ValueError is raised.
a.remove(0)
a.remove(9)
# a: [1, 2, 3, 4, 5, 6, 7, 8]
a.remove(10)
# ValueError, because 10 is not in a
a.reverse()
# a: [8, 7, 6, 5, 4, 3, 2, 1]
a.count(7)
# Returns: 2
9. sort() – sorts the list in numerical and lexicographical order and returns None.
a.sort()
# a = [1, 2, 3, 4, 5, 6, 7, 8]
# Sorts the list in numerical order
Lists can also be reversed when sorted using the reverse=True flag in the sort() method.
a.sort(reverse=True)
# a = [8, 7, 6, 5, 4, 3, 2, 1]
If you want to sort by attributes of items, you can use the key keyword argument:
import datetime
class Person(object):
def __init__(self, name, birthday, height):
self.name = name
self.birthday = birthday
self.height = height
def __repr__(self):
return self.name
import datetime
import datetime
Lists can also be sorted using attrgetter and itemgetter functions from the operator module. These can help
improve readability and reusability. Here are some examples,
people = [{'name':'chandan','age':20,'salary':2000},
{'name':'chetan','age':18,'salary':5000},
{'name':'guru','age':30,'salary':3000}]
by_age = itemgetter('age')
by_salary = itemgetter('salary')
itemgetter can also be given an index. This is helpful if you want to sort based on indices of a tuple.
a.clear()
# a = []
11. Replication – multiplying an existing list by an integer will produce a larger list consisting of that many copies
of the original. This can be useful for example for list initialization:
b = ["blah"] * 3
# b = ["blah", "blah", "blah"]
Take care doing this if your list contains references to objects (eg a list of lists), see Common Pitfalls - List
multiplication and common references.
12. Element deletion – it is possible to delete multiple elements in the list using the del keyword and slice
notation:
a = list(range(10))
del a[::2]
# a = [1, 3, 5, 7, 9]
del a[-1]
# a = [1, 3, 5, 7]
del a[:]
# a = []
13. Copying
The default assignment "=" assigns a reference of the original list to the new name. That is, the original name
and new name are both pointing to the same list object. Changes made through any of them will be reflected
in another. This is often not what you intended.
b = a
a.append(6)
# b: [1, 2, 3, 4, 5, 6]
If you want to create a copy of the list you have below options.
new_list = old_list[:]
new_list = list(old_list)
import copy
new_list = copy.copy(old_list) #inserts references to the objects found in the original.
This is a little slower than list() because it has to find out the datatype of old_list first.
If the list contains objects and you want to copy them as well, use generic copy.deepcopy():
import copy
new_list = copy.deepcopy(old_list) #inserts copies of the objects found in the original.
Obviously the slowest and most memory-needing method, but sometimes unavoidable.
aa = a.copy()
# aa = [1, 2, 3, 4, 5]
lst = [1, 2, 3, 4]
lst[0] # 1
lst[1] # 2
Attempting to access an index outside the bounds of the list will raise an IndexError.
Negative indices are interpreted as counting from the end of the list.
lst[-1] # 4
lst[-2] # 3
lst[-5] # IndexError: list index out of range
lst[len(lst)-1] # 4
Lists allow to use slice notation as lst[start:end:step]. The output of the slice notation is a new list containing
elements from index start to end-1. If options are omitted start defaults to beginning of list, end to end of list and
step to 1:
lst[1:] # [2, 3, 4]
lst[:3] # [1, 2, 3]
lst[::2] # [1, 3]
lst[::-1] # [4, 3, 2, 1]
lst[-1:0:-1] # [4, 3, 2]
lst[5:8] # [] since starting index is greater than length of lst, returns empty list
lst[1:10] # [2, 3, 4] same as omitting ending index
With this in mind, you can print a reversed version of the list by calling
lst[::-1] # [4, 3, 2, 1]
When using step lengths of negative amounts, the starting index has to be greater than the ending index otherwise
the result will be an empty list.
lst[3:1:-1] # [4, 3]
reversed(lst)[0:2] # 0 = 1 -1
# 2 = 3 -1
The indices used are 1 less than those used in negative indexing and are reversed.
When lists are sliced the __getitem__() method of the list object is called, with a slice object. Python has a builtin
slice method to generate slice objects. We can use this to store a slice and reuse it later like so,
This can be of great use by providing slicing functionality to our objects by overriding __getitem__ in our class.
lst = []
if not lst:
print("list is empty")
# Output: foo
# Output: bar
# Output: baz
You can also get the position of each item at the same time:
for i in range(0,len(my_list)):
print(my_list[i])
#output:
>>>
foo
bar
Note that changing items in a list while iterating on it may have unexpected results:
# Output: foo
# Output: baz
In this last example, we deleted the first item at the first iteration, but that caused bar to be skipped.
'test' in lst
# Out: True
'toast' in lst
# Out: False
Note: the in operator on sets is asymptotically faster than on lists. If you need to use it many times on
potentially large lists, you may want to convert your list to a set, and test the presence of elements on
the set.
slst = set(lst)
'test' in slst
# Out: True
nums = [1, 1, 0, 1]
all(nums)
# False
chars = ['a', 'b', 'c', 'd']
all(chars)
# True
nums = [1, 1, 0, 1]
any(nums)
# True
vals = [None, None, None, False]
any(vals)
# False
While this example uses a list, it is important to note these built-ins work with any iterable, including generators.
In [4]: rev
Out[4]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Note that the list "numbers" remains unchanged by this operation, and remains in the same order it was originally.
You can also reverse a list (actually obtaining a copy, the original list is unaffected) by using the slicing syntax,
setting the third argument (the step) as -1:
In [2]: numbers[::-1]
Out[2]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
2. zip returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument
sequences or iterables:
# Output:
# a1 b1
# a2 b2
# a3 b3
If the lists have different lengths then the result will include only as many elements as the shortest one:
# Output:
# a1 b1
alist = []
len(list(zip(alist, blist)))
# Output:
# 0
For padding lists of unequal length to the longest one with Nones use itertools.zip_longest
(itertools.izip_longest in Python 2)
# Output:
# a1 b1 c1
# a2 None c2
# a3 None c3
# None None c4
Output:
len() also works on strings, dictionaries, and other data structures similar to lists.
Also note that the cost of len() is O(1), meaning it will take the same amount of time to get the length of a list
regardless of its length.
import collections
>>> collections.OrderedDict.fromkeys(names).keys()
# Out: ['aixk', 'duke', 'edik', 'tofp']
If one of the lists is contained at the start of the other, the shortest list wins.
print(alist[0][0][1])
#2
#Accesses second element in the first list in the first list
print(alist[1][1][2])
#10
#Accesses the third element in the second list in the second list
alist[0][0].append(11)
print(alist[0][0][2])
#11
#Appends 11 to the end of the first list in the first list
Note that this operation can be used in a list comprehension or even as a generator to produce efficiencies, e.g.:
alist[1].insert(2, 15)
#Inserts 15 into the third position in the second list
Another way to use nested for loops. The other way is better but I've needed to use this on occasion:
#[1, 2, 11]
#[3, 4]
#[5, 6, 7]
#[8, 9, 10]
#15
#[12, 13, 14]
print(alist[1][1:])
#[[8, 9, 10], 15, [12, 13, 14]]
#Slices still work
print(alist)
#[[[1, 2, 11], [3, 4]], [[5, 6, 7], [8, 9, 10], 15, [12, 13, 14]]]
my_list = [None] * 10
my_list = ['test'] * 10
For mutable elements, the same construct will result in all elements of the list referring to the same object, for
example, for a set:
>>> my_list=[{1}] * 10
Instead, to initialize the list with a fixed number of different mutable objects, use:
Each <element> in the <iterable> is plugged in to the <expression> if the (optional) <condition> evaluates to true
. All results are returned at once in the new list. Generator expressions are evaluated lazily, but list comprehensions
evaluate the entire iterator immediately - consuming memory proportional to the iterator's length.
The for expression sets x to each value in turn from (1, 2, 3, 4). The result of the expression x * x is appended
to an internal list. The internal list is assigned to the variable squares when completed.
Besides a speed increase (as explained here), a list comprehension is roughly equivalent to the following for-loop:
squares = []
for x in (1, 2, 3, 4):
squares.append(x * x)
# squares: [1, 4, 9, 16]
else
else can be used in List comprehension constructs, but be careful regarding the syntax. The if/else clauses should
be used before for loop, not after:
Note this uses a different language construct, a conditional expression, which itself is not part of the
comprehension syntax. Whereas the if after the for…in is a part of list comprehensions and used to filter elements
from the source iterable.
Double Iteration
Order of double iteration [... for x in ... for y in ...] is either natural or counter-intuitive. The rule of
thumb is to follow an equivalent for loop:
def foo(i):
return i, i + 0.5
for i in range(3):
for x in foo(i):
yield str(x)
This becomes:
[str(x)
for i in range(3)
for x in foo(i)
]
This can be compressed into one line as [str(x) for i in range(3) for x in foo(i)]
Before using list comprehension, understand the difference between functions called for their side effects
(mutating, or in-place functions) which usually return None, and functions that return an interesting value.
Many functions (especially pure functions) simply take an object and return some object. An in-place function
modifies the existing object, which is called a side effect. Other examples include input and output operations such
as printing.
list.sort() sorts a list in-place (meaning that it modifies the original list) and returns the value None. Therefore, it
won't work as expected in a list comprehension:
Using comprehensions for side-effects is possible, such as I/O or in-place functions. Yet a for loop is usually more
Instead use:
In some situations, side effect functions are suitable for list comprehension. random.randrange() has the side
effect of changing the state of the random number generator, but it also returns an interesting value. Additionally,
next() can be called on an iterator.
The following random value generator is not pure, yet makes sense as the random generator is reset every time the
expression is evaluated:
More complicated list comprehensions can reach an undesired length, or become less readable. Although less
common in examples, it is possible to break a list comprehension into multiple lines like so:
[
x for x
in 'foo'
if x not in 'bar'
]
This results in two calls to f(x) for 1,000 values of x: one call for generating the value and the other for checking the
if condition. If f(x) is a particularly expensive operation, this can have significant performance implications.
Worse, if calling f() has side effects, it can have surprising results.
Instead, you should evaluate the expensive operation only once for each value of x by generating an intermediate
iterable (generator expression) as follows:
Another way that could result in a more readable code is to put the partial result (v in the previous example) in an
iterable (such as a list or a tuple) and then iterate over it. Since v will be the only element in the iterable, the result is
that we now have a reference to the output of our slow function computed only once:
However, in practice, the logic of code can be more complicated and it's important to keep it readable. In general, a
separate generator function is recommended over a complex one-liner:
Another way to prevent computing f(x) multiple times is to use the @functools.lru_cache()(Python 3.2+)
decorator on f(x). This way since the output of f for the input x has already been computed once, the second
function invocation of the original list comprehension will be as fast as a dictionary lookup. This approach uses
memoization to improve efficiency, which is comparable to using generator expressions.
reduce(lambda x, y: x+y, l)
sum(l, [])
list(itertools.chain(*l))
The shortcuts based on + (including the implied use in sum) are, of necessity, O(L^2) when there are L sublists -- as
the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated,
and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the
end). So (for simplicity and without actual loss of generality) say you have L sublists of I items each: the first I items
are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the
sum of x for x from 1 to L excluded, i.e., I * (L**2)/2.
The list comprehension just generates one list, once, and copies each item over (from its original place of residence
to the result list) also exactly once.
A basic example:
As with a list comprehension, we can use a conditional statement inside the dict comprehension to produce only
the dict elements meeting some criterion.
Starting with a dictionary and using dictionary comprehension as a key-value pair filter
If you have a dict containing simple hashable values (duplicate values may have unexpected results):
and you wanted to swap the keys and values you can take several approaches depending on your coding style:
print(swapped)
# Out: {a: 1, b: 2, c: 3}
If your dictionary is large, consider importing itertools and utilize izip or imap.
Combine dictionaries and optionally override old values with a nested dictionary comprehension.
{**dict1, **dict2}
# Out: {'w': 1, 'x': 2, 'y': 2, 'z': 2}
Note: dictionary comprehensions were added in Python 3.0 and backported to 2.7+, unlike list comprehensions,
which were added in 2.0. Versions < 2.7 can use generator expressions and the dict() builtin to simulate the
behavior of dictionary comprehensions.
# list comprehension
[x**2 for x in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# generator comprehension
(x**2 for x in xrange(10))
# Output: <generator object <genexpr> at 0x11b4b7c80>
the list comprehension returns a list object whereas the generator comprehension returns a generator.
generator objects cannot be indexed and makes use of the next function to get items in order.
Note: We use xrange since it too creates a generator object. If we would use range, a list would be created. Also,
xrange exists only in later version of python 2. In python 3, range just returns a generator. For more information,
see the Differences between range and xrange functions example.
g.next() # 0
g.next() # 1
NOTE: The function g.next() should be substituted by next(g) and xrange with range since
Iterator.next() and xrange() do not exist in Python 3.
"""
Out:
0
1
4
...
81
"""
"""
Out:
0
1
4
.
.
.
81
"""
Use cases
Generator expressions are lazily evaluated, which means that they generate and return each value only when the
generator is iterated. This is often useful when iterating through large datasets, avoiding the need to create a
duplicate of the dataset in memory:
Another common use case is to avoid iterating over an entire iterable if doing so is not necessary. In this example,
an item is retrieved from a remote API with each iteration of get_objects(). Thousands of objects may exist, must
be retrieved one-by-one, and we only need to know if an object matching a pattern exists. By using a generator
expression, when we encounter an object matching the pattern.
def object_matches_pattern(obj):
# perform potentially complex calculation
return matches_pattern
def right_item_exists():
items = (object_matched_pattern(each) for each in get_objects())
for item in items:
if item.is_the_right_one:
return True
return False
Live Demo
Keep in mind that sets are unordered. This means that the order of the results in the set may differ from the one
presented in the above examples.
Note: Set comprehension is available since python 2.7+, unlike list comprehensions, which were added in 2.0. In
Python 2.2 to Python 2.6, the set() function can be used with a generator expression to produce the same result:
Note however, if the expression that begins the comprehension is a tuple then it must be parenthesized:
# Count the numbers in `range(1000)` that are even and contain the digit `9`:
print (sum(
1 for x in range(1000)
if x % 2 == 0 and
'9' in str(x)
))
# Out: 95
Note: Here we are not collecting the 1s in a list (note the absence of square brackets), but we are passing the ones
directly to the sum function that is summing them up. This is called a generator expression, which is similar to a
Comprehension.
lst[::2]
# Output: ['a', 'c', 'e', 'g']
lst[::3]
# Output: ['a', 'd', 'g']
lst[2:4]
# Output: ['c', 'd']
lst[2:]
# Output: ['c', 'd', 'e']
lst[:4]
# Output: ['a', 'b', 'c', 'd']
if a = b:
print(True)
print(b)
# Output:
# True
# [5, 4, 3, 2, 1]
Args:
array - the list to shift
s - the amount to shift the list ('+': right-shift, '-': left-shift)
Returns:
shifted_array - the shifted list
return shifted_array
my_array = [1, 2, 3, 4, 5]
# negative numbers
shift_list(my_array, -7)
>>> [3, 4, 5, 1, 2]
class Node:
def __init__(self, val):
self.data = val
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
"""Check if the list is empty"""
return self.head is None
def size(self):
"""Return the length/size of the list"""
count = 0
current = self.head
while current is not None:
count += 1
current = current.getNext()
return count
current = self.head
if position is None:
ret = current.getData()
self.head = current.getNext()
else:
pos = 0
previous = None
while pos < position:
previous = current
current = current.getNext()
pos += 1
ret = current.getData()
previous.setNext(current.getNext())
print ret
return ret
def printList(self):
"""Print the list"""
current = self.head
while current is not None:
print current.getData()
current = current.getNext()
ll = LinkedList()
ll.add('l')
ll.add('H')
ll.insert(1,'e')
ll.append('l')
ll.append('o')
ll.printList()
#! /usr/bin/env python
class Node:
def __init__(self, cargo=None, next=None):
self.car = cargo
self.cdr = next
def __str__(self):
return str(self.car)
def display(lst):
if lst:
w("%s " % lst)
display(lst.cdr)
else:
w("nil\n")
t0 = ()
type(t0) # <type 'tuple'>
To create a tuple with a single element, you have to include a final comma:
t1 = 'a',
type(t1) # <type 'tuple'>
t2 = ('a')
type(t2) # <type 'str'>
t2 = ('a',)
type(t2) # <type 'tuple'>
Note that for singleton tuples it's recommended (see PEP8 on trailing commas) to use parentheses. Also, no white
space after the trailing comma (see PEP8 on whitespaces)
t2 = ('a',) # PEP8-compliant
t2 = 'a', # this notation is not recommended by PEP8
t2 = ('a', ) # this notation is not recommended by PEP8
t = tuple('lupins')
print(t) # ('l', 'u', 'p', 'i', 'n', 's')
t = tuple(range(3))
print(t) # (0, 1, 2)
These examples are based on material from the book Think Python by Allen B. Downey.
>>> t = (1, 4, 9)
>>> t[0] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Similarly, tuples don't have .append and .extend methods as list does. Using += is possible, but it changes the
binding of the variable, and not the tuple itself:
>>> t = (1, 2)
>>> q = t
>>> t += (3, 4)
>>> t
(1, 2, 3, 4)
>>> q
(1, 2)
Be careful when placing mutable objects, such as lists, inside tuples. This may lead to very confusing outcomes
when changing them. For example:
Will both raise an error and change the contents of the list within the tuple:
You can use the += operator to "append" to a tuple - this works by creating a new tuple with the new element you
"appended" and assign it to its current variable; the old tuple is not changed, but replaced!
This avoids converting to and from a list, but this is slow and is a bad practice, especially if you're going to append
multiple times.
and
are equivalent. The assignment a = 1, 2, 3 is also called packing because it packs values together in a tuple.
Note that a one-value tuple is also a tuple. To tell Python that a variable is a tuple and not a single value you can use
a = 1 # a is the value 1
a = 1, # a is the tuple (1,)
The symbol _ can be used as a disposable variable name if one only needs some elements of a tuple, acting as a
placeholder:
a = 1, 2, 3, 4
_, x, y, _ = a
# x == 2
# y == 3
x, = 1, # x is the value 1
x = 1, # x is the tuple (1,)
In Python 3 a target variable with a * prefix can be used as a catch-all variable (see Unpacking Iterables ):
Comparison
If elements are of the same type, python performs the comparison and returns the result. If elements are different
types, it checks whether they are numbers.
If we reached the end of one of the lists, the longer list is "larger." If both list are same it returns 0.
cmp(tuple1, tuple2)
Out: 1
cmp(tuple2, tuple1)
Out: -1
cmp(tuple1, tuple3)
Out: 0
Tuple Length
len(tuple1)
Out: 5
Max of a tuple
The function max returns item from the tuple with the max value
max(tuple1)
Out: 'e'
max(tuple2)
Out: '3'
Min of a tuple
The function min returns the item from the tuple with the min value
min(tuple1)
Out: 'a'
min(tuple2)
Out: '1'
list = [1,2,3,4,5]
tuple(list)
Out: (1, 2, 3, 4, 5)
Tuple concatenation
tuple1 + tuple2
Out: ('a', 'b', 'c', 'd', 'e', '1', '2', '3')
Thus a tuple can be put inside a set or as a key in a dict only if each of its elements can.
{ (1, 2) } # ok
Indexing with negative numbers will start from the last element as -1:
x[-1] # 3
x[-2] # 2
x[-3] # 1
x[-4] # IndexError: tuple index out of range
print(x[:-1]) # (1, 2)
print(x[-1:]) # (3,)
print(x[1:3]) # (2, 3)
rev = tuple(reversed(colors))
# rev: ("blue", "green", "red")
colors = rev
# colors: ("blue", "green", "red")
Functions in Python provide organized, reusable and modular code to perform a set of specific actions. Functions
simplify the coding process, prevent redundant logic, and make the code easier to follow. This topic describes the
declaration and utilization of functions in Python.
Python has many built-in functions like print(), input(), len(). Besides built-ins you can also create your own
functions to do more specific jobs—these are called user-defined functions.
def function_name(parameters):
statement(s)
function_name is known as the identifier of the function. Since a function definition is an executable statement its
execution binds the function name to the function object which can be called later on using the identifier.
parameters is an optional list of identifiers that get bound to the values supplied as arguments when the function is
called. A function may have an arbitrary number of arguments which are separated by commas.
statement(s) – also known as the function body – are a nonempty sequence of statements executed each time the
function is called. This means a function body cannot be empty, just like any indented block.
Here’s an example of a simple function definition which purpose is to print Hello each time it’s called:
def greet():
print("Hello")
greet()
# Out: Hello
That’s an other example of a function definition which takes one single argument and displays the passed in value
each time the function is called:
def greet_two(greeting):
print(greeting)
greet_two("Howdy")
# Out: Howdy
greet_two()
# Out: Howdy
You'll notice that unlike many other languages, you do not need to explicitly declare a return type of the function.
Python functions can return values of any type via the return keyword. One function can return any number of
different types!
def many_types(x):
if x < 0:
return "Hello!"
else:
return 0
print(many_types(1))
print(many_types(-1))
# Output:
0
Hello!
As long as this is handled correctly by the caller, this is perfectly valid Python code.
A function that reaches the end of execution without a return statement will always return None:
def do_nothing():
pass
print(do_nothing())
# Out: None
As mentioned previously a function definition must have a function body, a nonempty sequence of statements.
Therefore the pass statement is used as function body, which is a null operation – when it is executed, nothing
happens. It does what it means, it skips. It is useful as a placeholder when a statement is required syntactically, but
no code needs to be executed.
Defining a function capable of taking an arbitrary number of arguments can be done by prefixing one of the
arguments with a *
def func(*args):
# args will be a tuple containing all values that are passed in
for i in args:
print(i)
You can't provide a default for args, for example func(*args=[1, 2, 3]) will raise a syntax error (won't even
compile).
You can't provide these by name when calling the function, for example func(*args=[1, 2, 3]) will raise a
TypeError.
But if you already have your arguments in an array (or any other Iterable), you can invoke your function like this:
func(*my_stuff).
These arguments (*args) can be accessed by index, for example args[0] will return the first argument
You can take an arbitrary number of arguments with a name by defining an argument in the definition with two *
in front of it:
def func(**kwargs):
# kwargs will be a dictionary containing the names as keys and the values as values
for name, value in kwargs.items():
print(name, value)
You can't provide these without names, for example func(1, 2, 3) will raise a TypeError.
kwargs is a plain native python dictionary. For example, args['value1'] will give the value for argument value1. Be
sure to check beforehand that there is such an argument or a KeyError will be raised.
Warning
You can mix these with other optional and required arguments but the order inside the definition matters.
arg1 must be given, otherwise a TypeError is raised. It can be given as positional (func(10)) or keyword
argument (func(arg1=10)).
kwarg1 must also be given, but it can only be provided as keyword-argument: func(kwarg1=10).
arg2 and kwarg2 are optional. If the value is to be changed the same rules as for arg1 (either positional or
keyword) and kwarg1 (only keyword) apply.
*args catches additional positional parameters. But note, that arg1 and arg2 must be provided as positional
arguments to pass arguments to *args: func(1, 1, 1, 1).
**kwargs catches all additional keyword parameters. In this case any parameter that is not arg1, arg2,
kwarg1 or kwarg2. For example: func(kwarg3=10).
In Python 3, you can use * alone to indicate that all subsequent arguments must be specified as keywords.
For instance the math.isclose function in Python 3.5 and higher is defined using def math.isclose (a, b,
*, rel_tol=1e-09, abs_tol=0.0), which means the first two arguments can be supplied positionally but the
optional third and fourth parameters can only be supplied as keyword arguments.
Python 2.x doesn't support keyword-only parameters. This behavior can be emulated with kwargs:
kwarg2 = kwargs.pop("kwarg2", 2)
# function body ...
Note on Naming
The convention of naming optional positional arguments args and optional keyword arguments kwargs is just a
convention you can use any names you like but it is useful to follow the convention so that others know what you
are doing, or even yourself later so please do.
Note on Uniqueness
Any function can be defined with none or one *args and none or one **kwargs but not with more than one of
each. Also *args must be the last positional argument and **kwargs must be the last parameter. Attempting to use
more than one of either will result in a Syntax Error exception.
It is possible to nest such functions and the usual convention is to remove the items that the code has already
handled but if you are passing down the parameters you need to pass optional positional args with a * prefix and
optional keyword args with a ** prefix, otherwise args with be passed as a list or tuple and kwargs as a single
dictionary. e.g.:
def fn(**kwargs):
print(kwargs)
f1(**kwargs)
def f1(**kwargs):
print(len(kwargs))
fn(a=1, b=2)
def greeting():
return "Hello"
print(greeting())
prints:
Hello
See note at the bottom of this section regarding the assignment of lambdas to variables. Generally, don't
do it.
This creates an inline function with the name greet_me that returns Hello. Note that you don't write return when
creating a function with lambda. The value after : is automatically returned.
print(greet_me())
prints:
Hello
HELLO
They can also take arbitrary number of arguments / keyword arguments, like normal functions.
prints:
lambdas are commonly used for short functions that are convenient to define at the point where they are called
(typically with sorted, filter and map).
For example, this line sorts a list of strings ignoring their case and ignoring whitespace at the beginning and at the
end:
sorted( [" foo ", " bAR", "BaZ "], key=lambda s: s.strip().upper())
# Out:
# [' bAR', 'BaZ ', ' foo ']
sorted( [" foo ", " bAR", "BaZ "], key=lambda s: s.strip())
# Out:
# ['BaZ ', ' bAR', ' foo ']
sorted( map( lambda s: s.strip().upper(), [" foo ", " bAR", "BaZ "]))
# Out:
# ['BAR', 'BAZ', 'FOO']
sorted( map( lambda s: s.strip(), [" foo ", " bAR", "BaZ "]))
# Out:
# ['BaZ', 'bAR', 'foo']
One can call other functions (with/without arguments) from inside a lambda function.
def foo(msg):
print(msg)
prints:
This is useful because lambda may contain only one expression and by using a subsidiary function one can run
multiple statements.
NOTE
Bear in mind that PEP-8 (the official Python style guide) does not recommend assigning lambdas to variables (as we
did in the first two examples):
Always use a def statement instead of an assignment statement that binds a lambda expression directly
to an identifier.
Yes:
No:
f = lambda x: 2*x
The first form means that the name of the resulting function object is specifically f instead of the generic
<lambda>. This is more useful for tracebacks and string representations in general. The use of the
assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def
statement (i.e. that it can be embedded inside a larger expression).
def make(action='nothing'):
return action
make("fun")
# Out: fun
make(action="sleep")
# Out: sleep
# The argument is optional so the function will use the default value if the argument is
# not passed in.
make()
# Out: nothing
Warning
Mutable types (list, dict, set, etc.) should be treated with care when given as default attribute. Any
mutation of the default argument will change it permanently. See Defining a function with optional
mutable arguments.
Explanation
This problem arises because a function's default arguments are initialised once, at the point when the function is
defined, and not (like many other languages) when the function is called. The default values are stored inside the
function object's __defaults__ member variable.
print(f.__defaults__)
# Out: (42, [])
For immutable types (see Argument passing and mutability) this is not a problem because there is no way to
mutate the variable; it can only ever be reassigned, leaving the original value unchanged. Hence, subsequent are
guaranteed to have the same default value. However, for a mutable type, the original value can mutate, by making
calls to its various member functions. Therefore, successive calls to the function are not guaranteed to have the
initial default value.
append(1)
# Out: [1]
append(3, []) # Using a new created list gives the expected result
# Out: [3]
# Calling it again without argument will append to the internally stored list again
append(4)
# Out: [1, 2, 4]
Note: Some IDEs like PyCharm will issue a warning when a mutable type is specified as a default
attribute.
Solution
If you want to ensure that the default argument is always the one you specify in the function definition, then the
solution is to always use an immutable type as your default argument.
A common idiom to achieve this when a mutable type is needed as the default, is to use None (immutable) as the
default argument and then assign the actual default value to the argument variable if it is equal to None.
In Python, arguments are passed by assignment (as opposed to other languages, where arguments can be
passed by value/reference/pointer).
Mutating a parameter will mutate the argument (if the argument's type is mutable).
y = [4, 5, 6]
foo(y) # call foo with y as argument
# Out: [9, 5, 6] # list labelled by x has been mutated
print(y)
# Out: [9, 5, 6] # list labelled by y has been mutated too
In Python, we don’t really assign values to variables, instead we bind (i.e. assign, attach) variables
(considered as names) to objects.
Immutable: Integers, strings, tuples, and so on. All operations make copies.
Mutable: Lists, dictionaries, sets, and so on. Operations may or may not mutate.
x = [3, 1, 9]
y = x
x.append(5) # Mutates the list labelled by x and y, both x and y are bound to [3, 1, 9]
x.sort() # Mutates the list labelled by x and y (in-place sorting)
x = x + [4] # Does not mutate the list (makes a copy for x only, not y)
z = x # z is x ([1, 3, 9, 4])
x += [6] # Mutates the list labelled by both x and z (uses the extend function).
x = sorted(x) # Does not mutate the list (makes a copy for x only).
x
# Out: [1, 3, 4, 5, 6, 9]
y
# Out: [1, 3, 5, 9]
z
def give_me_five():
return 5
num = give_me_five()
print(num) # Print the saved returned value
# Out: 5
print(give_me_five() + 10)
# Out: 15
If return is encountered in the function the function will be exited immediately and subsequent operations will not
be evaluated:
def give_me_another_five():
return 5
print('This statement will not be printed. Ever.')
print(give_me_another_five())
# Out: 5
You can also return multiple values (in the form of a tuple):
def give_me_two_fives():
return 5, 5 # Returns two 5
A function with no return statement implicitly returns None. Similarly a function with a return statement, but no
return value or variable returns None.
def makeInc(x):
def inc(y):
# x is "attached" in the definition of inc
return inc
incOne = makeInc(1)
incFive = makeInc(5)
incOne(5) # returns 6
incFive(5) # returns 10
Notice that while in a regular closure the enclosed function fully inherits all variables from its enclosing
environment, in this construct the enclosed function has only read access to the inherited variables but cannot
make assignments to them
def makeInc(x):
def inc(y):
# incrementing x is not allowed
x += y
return x
return inc
incOne = makeInc(1)
incOne(5) # UnboundLocalError: local variable 'x' referenced before assignment
Python 3 offers the nonlocal statement (Nonlocal Variables ) for realizing a full closure with nested functions.
def makeInc(x):
def inc(y):
nonlocal x
# now assigning a value to x is allowed
x += y
return x
return inc
incOne = makeInc(1)
incOne(5) # returns 6
f(1, 2, 3)
# TypeError: f() missing 1 required keyword-only argument: 'b'
In Python 3 it's possible to put a single asterisk in the function signature to ensure that the remaining arguments
may only be passed using keyword arguments.
f(1, 2, 3)
# TypeError: f() takes 2 positional arguments but 3 were given
def fibonacci(n):
def step(a,b):
return b, a+b
a, b = 0, 1
for i in range(n):
a, b = step(a, b)
return a
Functions capture their enclosing scope can be passed around like any other sort of object
def make_adder(n):
def adder(x):
return n + x
return adder
add5 = make_adder(5)
add6 = make_adder(6)
add5(10)
#Out: 15
add6(10)
#Out: 16
repeatedly_apply(add5, 5, 1)
#Out: 26
def cursing(depth):
try:
cursing(depth + 1) # actually, re-cursing
except RuntimeError as RE:
print('I recursed {} times!'.format(depth))
cursing(0)
# Out: I recursed 1083 times!
It is possible to change the recursion depth limit by using sys.setrecursionlimit(limit) and check this limit by
sys.getrecursionlimit().
sys.setrecursionlimit(2000)
cursing(0)
# Out: I recursed 1997 times!
Description of code
The lambda function, through its variable assignment, is passed a value (4) which it evaluates and returns 1 if it is 0
or else it returns the current value (i) * another calculation by the lambda function of the value - 1 (i-1). This
continues until the passed value is decremented to 0 (return 1). A process which can be visualized as:
def factorial(n):
factorial(0)
#out 1
factorial(1)
#out 1
factorial(2)
#out 2
factorial(3)
#out 6
as expected. Notice that this function is recursive because the second return factorial(n-1), where the function
calls itself in its definition.
Some recursive functions can be implemented using lambda, the factorial function using lambda would be
something like this:
def divide(dividend, divisor): # The names of the function and its arguments
# The arguments are available by name in the body of the function
print(dividend / divisor)
The function name and its list of arguments are called the signature of the function. Each named argument is
effectively a local variable of the function.
When calling the function, give values for the arguments by listing them in order
divide(10, 2)
# output: 5
or specify them in any order using the names from the function definition:
divide(divisor=2, dividend=10)
# output: 5
# Positional arguments take priority over any other form of argument passing
>>> unpacking(1, 2, **arg_dict, c=3)
1 2 3 4 () {'not_a_parameter': 75}
>>> unpacking(1, 2, 3, **arg_dict, c=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unpacking() got multiple values for argument 'c'
When calling the function you can either give each keyword without the name but then the order matters:
print(func('abc', 14))
# abc 14 10
Or combine giving the arguments with name and without. Then the ones with name must follow those without but
the order of the ones with name doesn't matter:
def func(myList):
for item in myList:
print(item)
func([1,2,3,5,7])
1
2
3
5
7
Or as a variable:
aList = ['a','b','c','d']
func(aList)
a
b
c
d
s=lambda x:x*x
s(2) =>4
This is a simple map that takes a list of names and returns a list of the lengths of those names:
This is a simple reduce. It returns the sum of all the items in the collection.
arr=[1,2,3,4,5,6]
[i for i in filter(lambda x:x>4,arr)] # outputs[5,6]
As you probably know if you came from OOP school, specializing an abstract class and use it is a practice you
should keep in mind when writing your code.
What if you could define an abstract function and specialize it in order to create different versions of it? Thinks it as
a sort of function Inheritance where you bind specific params to make them reliable for a specific scenario.
Let's suppose y can be one of [3,4,5] and let's say you don't want offer end user the possibility to use such function
since it is very computationally intensive. In fact you would check if provided y assumes a valid value and rewrite
your function as:
Messy? Let's use the abstract form and specialize it to all three cases: let's implement them partially.
What happens here? We fixed the y params and we defined three different functions.
No need to use the abstract function defined above (you could make it private) but you could use partial applied
functions to deal with raising a number to a fixed value.
Decorator functions are software design patterns. They dynamically alter the functionality of a function, method, or
class without having to directly use subclasses or change the source code of the decorated function. When used
correctly, decorators can become powerful tools in the development process. This topic covers implementation and
applications of decorator functions in Python.
# This simplest decorator does nothing to the function being decorated. Such
# minimal decorators can occasionally be used as a kind of code markers.
def super_secret_function(f):
return f
@super_secret_function
def my_function():
print("This is my secret function.")
my_function = super_secret_function(my_function)
It is important to bear this in mind in order to understand how the decorators work. This "unsugared" syntax makes
it clear why the decorator function takes a function as an argument, and why it should return another function. It
also demonstrates what would happen if you don't return a function:
def disabled(f):
"""
This function returns nothing, and hence removes the decorated function
from the local scope.
"""
pass
@disabled
def my_function():
print("This function can no longer be called...")
my_function()
# TypeError: 'NoneType' object is not callable
Thus, we usually define a new function inside the decorator and return it. This new function would first do
something that it needs to do, then call the original function, and finally process the return value. Consider this
simple decorator function that prints the arguments that the original function receives, then calls it.
@print_args
def multiply(num_a, num_b):
return num_a * num_b
print(multiply(3, 5))
#Output:
# (3,5) - This is actually the 'args' that the function receives.
# {} - This is the 'kwargs', empty because we didn't specify keyword arguments.
# 15 - The result of the function.
class Decorator(object):
"""Simple decorator class."""
@Decorator
def testfunc():
print('Inside the function.')
testfunc()
# Before the function call.
# Inside the function.
# After the function call.
Note that a function decorated with a class decorator will no longer be considered a "function" from type-checking
perspective:
import types
isinstance(testfunc, types.FunctionType)
# False
type(testfunc)
# <class '__main__.Decorator'>
Decorating Methods
class Decorator(object):
def __init__(self, func):
self.func = func
class Test(object):
@Decorator
def __init__(self):
pass
a = Test()
Warning!
Class Decorators only produce one instance for a specific function so decorating a method with a class decorator
will share the same decorator between all instances of that class:
class CountCallsDecorator(object):
def __init__(self, func):
self.func = func
self.ncalls = 0 # Number of calls of this method
class Test(object):
def __init__(self):
pass
@CountCallsDecorator
def do_something(self):
return 'something was done'
a = Test()
a.do_something()
a.do_something.ncalls # 1
b = Test()
b.do_something()
b.do_something.ncalls # 2
But additional arguments are often desired. The trick is then to make a function which takes arbitrary arguments
and returns a decorator.
@decoratorfactory('Hello World')
def test():
pass
test()
Important Note:
With such decorator factories you must call the decorator with a pair of parentheses:
test()
Decorator classes
def decoratorfactory(*decorator_args, **decorator_kwargs):
class Decorator(object):
def __init__(self, func):
self.func = func
return Decorator
@decoratorfactory(10)
def test():
pass
test()
The two methods of wrapping a decorator are achieving the same thing in hiding that the original function has
been decorated. There is no reason to prefer the function version to the class version unless you're already using
one over the other.
As a function
def decorator(func):
# Copies the docstring, name, annotations and module to the decorator
@wraps(func)
def wrapped_func(*args, **kwargs):
return func(*args, **kwargs)
return wrapped_func
@decorator
def test():
pass
test.__name__
'test'
As a class
class Decorator(object):
def __init__(self, func):
# Copies name, module, annotations and docstring to the instance.
self._wrapped = wraps(func)(self)
@Decorator
def test():
"""Docstring of test."""
pass
test.__doc__
'Docstring of test.'
@timer
def example_function():
#do stuff
example_function()
def singleton(cls):
instance = [None]
def wrapper(*args, **kwargs):
if instance[0] is None:
instance[0] = cls(*args, **kwargs)
return instance[0]
return wrapper
This decorator can be added to any class declaration and will make sure that at most one instance of the class is
created. Any subsequent calls will return the already existing class instance.
@singleton
class SomeSingletonClass:
x = 2
def __init__(self):
print("Created!")
instance.x = 3
print(SomeSingletonClass().x) # 3
So it doesn't matter whether you refer to the class instance via your local variable or whether you create another
"instance", you always get the same object.
class Person(object):
"""A simple class.""" # docstring
species = "Homo Sapiens" # class attribute
There are a few things to note when looking at the above example.
>>> # Instances
>>> kelly = Person("Kelly")
>>> joseph = Person("Joseph")
>>> john_doe = Person("John Doe")
We can access the attributes of the class from each instance using the dot operator . Note again the difference
between class and instance attributes:
>>> # Attributes
>>> kelly.species
'Homo Sapiens'
>>> john_doe.species
'Homo Sapiens'
>>> joseph.species
'Homo Sapiens'
>>> kelly.name
'Kelly'
>>> joseph.name
'Joseph'
We can execute the methods of the class using the same dot operator .:
>>> # Methods
>>> john_doe.__str__()
'John Doe'
>>> print(john_doe)
'John Doe'
>>> john_doe.rename("John")
'Now my name is John'
class A(object):
def f(self, x):
return 2 * x
A.f
# <function A.f at ...> (in Python 3.x)
In Python 2 the behavior was different: function objects within the class were implicitly replaced with objects of type
instancemethod, which were called unbound methods because they were not bound to any particular class instance.
It was possible to access the underlying function using .__func__ property.
A.f
The latter behaviors are confirmed by inspection - methods are recognized as functions in Python 3, while the
distinction is upheld in Python 2.
import inspect
inspect.isfunction(A.f)
# True
inspect.ismethod(A.f)
# False
import inspect
inspect.isfunction(A.f)
# False
inspect.ismethod(A.f)
# True
In both versions of Python function/method A.f can be called directly, provided that you pass an instance of class A
as the first argument.
A.f(1, 7)
# Python 2: TypeError: unbound method f() must be called with
# A instance as first argument (got int instance instead)
# Python 3: 14
a = A()
A.f(a, 20)
# Python 2 & 3: 40
Now suppose a is an instance of class A, what is a.f then? Well, intuitively this should be the same method f of class
A, only it should somehow "know" that it was applied to the object a – in Python this is called method bound to a.
The nitty-gritty details are as follows: writing a.f invokes the magic __getattribute__ method of a, which first
checks whether a has an attribute named f (it doesn't), then checks the class A whether it contains a method with
such a name (it does), and creates a new object m of type method which has the reference to the original A.f in
m.__func__, and a reference to the object a in m.__self__. When this object is called as a function, it simply does
the following: m(...) => m.__func__(m.__self__, ...). Thus this object is called a bound method because when
invoked it knows to supply the object it was bound to as the first argument. (These things work same way in Python
2 and 3).
a = A()
a.f
# <bound method A.f of <__main__.A object at ...>>
a.f(2)
# 4
# Note: the bound method object a.f is recreated *every time* you call it:
a.f is a.f # False
# As a performance optimization you can store the bound method in the object's
# __dict__, in which case the method object will remain fixed:
a.f = a.f
Finally, Python has class methods and static methods – special kinds of methods. Class methods work the same
way as regular methods, except that when invoked on an object they bind to the class of the object instead of to the
object. Thus m.__self__ = type(a). When you call such bound method, it passes the class of a as the first
argument. Static methods are even simpler: they don't bind anything at all, and simply return the underlying
function without any transformations.
class D(object):
multiplier = 2
@classmethod
def f(cls, x):
return cls.multiplier * x
@staticmethod
def g(name):
print("Hello, %s" % name)
D.f
# <bound method type.f of <class '__main__.D'>>
D.f(12)
# 24
D.g
# <function D.g at ...>
D.g("world")
# Hello, world
Note that class methods are bound to the class even when accessed on the instance:
d = D()
d.multiplier = 1337
(D.multiplier, d.multiplier)
# (2, 1337)
d.f
# <bound method D.f of <class '__main__.D'>>
d.f(10)
# 20
It is worth noting that at the lowest level, functions, methods, staticmethods, etc. are actually descriptors that
invoke __get__, __set__ and optionally __del__ special methods. For more details on classmethods and
staticmethods:
class BaseClass(object):
pass
class DerivedClass(BaseClass):
pass
We define a parent Rectangle class in the example below, which implicitly inherits from object:
class Rectangle():
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def perimeter(self):
return 2 * (self.w + self.h)
The Rectangle class can be used as a base class for defining a Square class, as a square is a special case of
rectangle.
class Square(Rectangle):
def __init__(self, s):
# call parent constructor, w and h are both s
super(Square, self).__init__(s, s)
self.s = s
The Square class will automatically inherit all attributes of the Rectangle class as well as the object class. super() is
used to call the __init__() method of Rectangle class, essentially calling any overridden method of the base class.
Note: in Python 3, super() does not require arguments.
Derived class objects can access and modify the attributes of its base classes:
r.area()
# Output: 12
r.perimeter()
# Output: 14
s.area()
# Output: 4
s.perimeter()
# Output: 8
isinstance(s, Class): returns True if s is an instance of Class or any of the derived classes of Class
# subclass check
issubclass(Square, Rectangle)
# Output: True
# instantiate
r = Rectangle(3, 4)
s = Square(2)
isinstance(r, Rectangle)
# Output: True
isinstance(r, Square)
isinstance(s, Rectangle)
# Output: True
# A square is a rectangle
isinstance(s, Square)
# Output: True
class A(object):
def __init__(self, num):
self.num = num
But now we want to add another function later in the code. Suppose this function is as follows.
def get_num(self):
return self.num
But how do we add this as a method in A? That's simple we just essentially place that function into A with an
assignment statement.
A.get_num = get_num
Why does this work? Because functions are objects just like any other object, and methods are functions that
belong to the class.
The function get_num shall be available to all existing (already created) as well to the new instances of A
These additions are available on all instances of that class (or its subclasses) automatically. For example:
foo = A(42)
A.get_num = get_num
bar = A(6);
foo.get_num() # 42
bar.get_num() # 6
Note that, unlike some other languages, this technique does not work for certain built-in types, and it is not
considered good style.
New-style classes were introduced in Python 2.2 to unify classes and types. They inherit from the top-level object
# new-style class
class New(object):
pass
# new-style instance
new = New()
new.__class__
# <class '__main__.New'>
type(new)
# <class '__main__.New'>
issubclass(New, object)
# True
Old-style classes do not inherit from object. Old-style instances are always implemented with a built-in instance
type.
# old-style class
class Old:
pass
# old-style instance
old = Old()
old.__class__
# <class __main__.Old at ...>
type(old)
# <type 'instance'>
issubclass(Old, object)
# False
New-style classes in Python 3 implicitly inherit from object, so there is no need to specify MyClass(object)
anymore.
class MyClass:
pass
my_inst = MyClass()
type(my_inst)
# <class '__main__.MyClass'>
my_inst.__class__
# <class '__main__.MyClass'>
issubclass(MyClass, object)
# True
class Person(object):
def greet(self):
print("Hello, my name is " + self.full_name + ".")
It might be handy to have a way to build instances of this class specifying a full name instead of first and last name
separately. One way to do this would be to have last_name be an optional parameter, and assuming that if it isn't
given, we passed the full name in:
class Person(object):
def greet(self):
print("Hello, my name is " + self.full_name + ".")
However, there are two main problems with this bit of code:
1. The parameters first_name and last_name are now misleading, since you can enter a full name for
first_name. Also, if there are more cases and/or more parameters that have this kind of flexibility, the
if/elif/else branching can get annoying fast.
2. Not quite as important, but still worth pointing out: what if last_name is None, but first_name doesn't split
into two or more things via spaces? We have yet another layer of input validation and/or exception
handling...
Enter class methods. Rather than having a single initializer, we will create a separate initializer, called
from_full_name, and decorate it with the (built-in) classmethod decorator.
class Person(object):
@classmethod
def from_full_name(cls, name, age):
if " " not in name:
raise ValueError
first_name, last_name = name.split(" ", 2)
return cls(first_name, last_name, age)
def greet(self):
print("Hello, my name is " + self.full_name + ".")
To show that this works as expected, let's create instances of Person in more than one way without the branching
in __init__:
In [4]: bob.greet()
Hello, my name is Bob Bobberson.
In [5]: alice.greet()
Hello, my name is Alice Henderson.
Other references:
https://docs.python.org/2/library/functions.html#classmethod
https://docs.python.org/3.5/library/functions.html#classmethod
class Foo(object):
foo = 'attr foo of Foo'
class Bar(object):
foo = 'attr foo of Bar' # we won't see this.
bar = 'attr bar of Bar'
Now if we instantiate FooBar, if we look up the foo attribute, we see that Foo's attribute is found first
fb = FooBar()
and
>>> fb.foo
'attr foo of Foo'
That is, for example, Bar cannot inherit from FooBar while FooBar inherits from Bar.
Another powerful feature in inheritance is super. super can fetch parent classes features.
class Foo(object):
def foo_method(self):
print "foo Method"
class Bar(object):
def bar_method(self):
print "bar Method"
Multiple inheritance with init method of class, when every class has own init method then we try for multiple
ineritance then only init method get called of class which is inherit first.
for below example only Foo class init method getting called Bar class init not getting called
class Foo(object):
def __init__(self):
print "foo init"
class Bar(object):
def __init__(self):
print "bar init"
a = FooBar()
Output:
foobar init
foo init
But it doesn't mean that Bar class is not inherit. Instance of final FooBar class is also instance of Bar class and Foo
class.
print isinstance(a,FooBar)
print isinstance(a,Foo)
Output:
True
True
True
class MyClass(object):
def __init__(self):
self._my_string = ""
@property
def string(self):
"""A profoundly important string."""
return self._my_string
@string.setter
def string(self, new_value):
assert isinstance(new_value, str), \
"Give me a string, not a %r!" % type(new_value)
self._my_string = new_value
@string.deleter
def x(self):
self._my_string = None
The object's of class MyClass will appear to have have a property .string, however it's behavior is now tightly
controlled:
mc = MyClass()
mc.string = "String!"
print(mc.string)
del mc.string
As well as the useful syntax as above, the property syntax allows for validation, or other augmentations to be added
to those attributes. This could be especially useful with public APIs - where a level of help should be given to the
user.
Another common use of properties is to enable the class to present 'virtual attributes' - attributes which aren't
actually stored but are computed only when requested.
class Character(object):
def __init__(name, max_hp):
self._name = name
self._hp = max_hp
self._max_hp = max_hp
@property
def is_alive(self):
return self.hp != 0
@property
def is_wounded(self):
return self.hp < self.max_hp if self.hp > 0 else False
@property
def is_dead(self):
return not self.is_alive
bilbo.is_alive
# out : True
bilbo.is_wounded
# out : False
bilbo.is_dead
# out : False
bilbo.take_damage( 50 )
bilbo.hp
# out : 50
bilbo.is_alive
# out : True
bilbo.is_wounded
# out : True
bilbo.is_dead
# out : False
bilbo.take_damage( 50 )
bilbo.hp
# out : 0
bilbo.is_alive
# out : False
bilbo.is_wounded
# out : False
bilbo.is_dead
# out : True
def area(self):
return self.width * self.height
One needs to be careful when initializing mutable objects such as lists in the constructor. Consider the following
example:
class Rectangle2D(object):
def __init__(self, width, height, pos=[0,0], color='blue'):
self.width = width
self.height = height
self.pos = pos
self.color = color
r1 = Rectangle2D(5,3)
r2 = Rectangle2D(7,8)
r1.pos[0] = 4
r1.pos # [4, 0]
r2.pos # [4, 0] r2's pos has changed as well
This behavior is caused by the fact that in Python default parameters are bound at function execution and not at
function declaration. To get a default instance variable that's not shared among instances, one should use a
construct like this:
class Rectangle2D(object):
def __init__(self, width, height, pos=None, color='blue'):
self.width = width
self.height = height
self.pos = pos or [0, 0] # default value is [0, 0]
self.color = color
r1 = Rectangle2D(5,3)
r2 = Rectangle2D(7,8)
r1.pos[0] = 4
r1.pos # [4, 0]
r2.pos # [0, 0] r2's pos hasn't changed
See also Mutable Default Arguments and “Least Astonishment” and the Mutable Default Argument.
class C:
x = 2 # class variable
C.x
# 2
C.y
# AttributeError: type object 'C' has no attribute 'y'
c1 = C(3)
c1.x
# 2
c1.y
# 3
c2 = C(4)
c2.x
# 2
c2.y
# 4
Class variables can be accessed on instances of this class, but assigning to the class attribute will create an instance
variable which shadows the class variable
c2.x = 4
c2.x
# 4
C.x
# 2
Note that mutating class variables from instances can lead to some unexpected consequences.
class D:
x = []
def __init__(self, item):
self.x.append(item) # note that this is not an assigment!
d1 = D(1)
d2 = D(2)
d1.x
# [1, 2]
d2.x
# [1, 2]
D.x
# [1, 2]
class Country(object):
def __init__(self):
self.cities=[]
def addCity(self,city):
self.cities.append(city)
def join_country(self,country):
self.country = country
country.addCity(self)
for i in range(self.numPeople):
person(i).join_city(self)
class Person(object):
def __init__(self, ID):
self.ID=ID
def people_in_my_country(self):
x= sum([len(c.people) for c in self.city.country.cities])
return x
US=Country()
NYC=City(10).join_country(US)
SF=City(5).join_country(US)
print(US.cities[0].people[0].people_in_my_country())
# 15
dir(Class)
For example:
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count',
'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
It is common to look only for "non-magic" members. This can be done using a simple comprehension that lists
members with names not starting with __:
Classes can define a __dir__() method. If that method exists calling dir() will call __dir__(), otherwise Python
will try to create a list of members of the class. This means that the dir function can have unexpected results. Two
quotes of importance from the official python documentation:
If the object does not provide dir(), the function tries its best to gather information from the object’s dict
attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be
inaccurate when the object has a custom getattr().
Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to
supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of
names, and its detailed behavior may change across releases. For example, metaclass attributes are not
in the result list when the argument is a class.
class Singleton:
def __new__(cls):
try:
it = cls.__it__
except AttributeError:
it = cls.__it__ = object.__new__(cls)
return it
def __repr__(self):
return '<{}>'.format(self.__class__.__name__.upper())
Another method is to decorate your class. Following the example from this answer create a Singleton class:
class Singleton:
"""
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
"""
def Instance(self):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `Instance()`.')
@Singleton
class Single:
def __init__(self):
self.name=None
self.val=0
def getName(self):
print(self.name)
x=Single.Instance()
y=Single.Instance()
x.name='I\'m single'
x.getName() # outputs I'm single
y.getName() # outputs I'm single
These can control the dotted lookup on an instance, and are used to implement functions, staticmethod,
classmethod, and property. A dotted lookup (e.g. instance foo of class Foo looking up attribute bar - i.e. foo.bar)
uses the following algorithm:
1. bar is looked up in the class, Foo. If it is there and it is a Data Descriptor, then the data descriptor is used.
That's how property is able to control access to data in an instance, and instances cannot override this. If a
Data Descriptor is not there, then
2. bar is looked up in the instance __dict__. This is why we can override or block methods being called from an
instance with a dotted lookup. If bar exists in the instance, it is used. If not, we then
3. look in the class Foo for bar. If it is a Descriptor, then the descriptor protocol is used. This is how functions
(in this context, unbound methods), classmethod, and staticmethod are implemented. Else it simply returns
the object there, or there is an AttributeError
class mytype(type):
def __init__(cls, name, bases, dict):
# call the base initializer
type.__init__(cls, name, bases, dict)
Now, we have a new custom mytype metaclass which can be used to create classes in the same manner as type.
When we create a new class using the class keyword the metaclass is by default chosen based on upon the
baseclasses.
>>> type(Foo)
type
In the above example the only baseclass is object so our metaclass will be the type of object, which is type. It is
possible override the default, however it depends on whether we use Python 2 or Python 3:
class MyDummy(object):
__metaclass__ = mytype
type(MyDummy) # <class '__main__.mytype'>
class MyDummy(metaclass=mytype):
Any keyword arguments (except metaclass) in the class declaration will be passed to the metaclass. Thus class
MyDummy(metaclass=mytype, x=2) will pass x=2 as a keyword argument to the mytype constructor.
class SingletonType(type):
def __call__(cls, *args, **kwargs):
try:
return cls.__instance
except AttributeError:
cls.__instance = super(SingletonType, cls).__call__(*args, **kwargs)
return cls.__instance
class MySingleton(object):
__metaclass__ = SingletonType
class MySingleton(metaclass=SingletonType):
pass
class MyClass(object):
__metaclass__ = SomeMetaclass
class MyClass(metaclass=SomeMetaclass):
pass
class MyClass(six.with_metaclass(SomeMetaclass)):
pass
In Python, everything is an object: integers, strings, lists, even functions and classes themselves are objects. And
every object is an instance of a class.
Most classes in python are instances of type. type itself is also a class. Such classes whose instances are also
classes are called metaclasses.
OK, so there is already one metaclass in Python: type. Can we create another one?
class SimplestMetaclass(type):
pass
class MyClass(object):
__metaclass__ = SimplestMetaclass
That does not add any functionality, but it is a new metaclass, see that MyClass is now an instance of
SimplestMetaclass:
>>> type(MyClass)
<class '__main__.SimplestMetaclass'>
A metaclass which does something usually overrides type's __new__, to modify some properties of the class to be
created, before calling the original __new__ which creates the class:
class AnotherMetaclass(type):
def __new__(cls, name, parents, dct):
# cls is this class
# name is the name of the class to be created
# parents is the list of the class's parent classes
# dct is the list of class's attributes (methods, static variables)
# here all of the attributes can be modified before creating the class, e.g.
# return value is the new class. super will take care of that
return super(AnotherMetaclass, cls).__new__(cls, name, parents, dct)
class VerboseMetaclass(type):
class Spam(metaclass=VerboseMetaclass):
def eggs(self):
print("[insert example string here]")
s = Spam()
s.eggs()
>>> type(1)
int
>>> type(bar)
Foo
Nice, bar is an instance of Foo. But what is the class of Foo itself?
>>> type(Foo)
type
>>> type(type)
type
So what is a metaclass? For now lets pretend it is just a fancy name for the class of a class. Takeaways:
str.casefold
str.upper
str.lower
str.capitalize
str.title
str.swapcase
With unicode strings (the default in Python 3), these operations are not 1:1 mappings or reversible. Most of these
operations are intended for display purposes, rather than normalization.
str.casefold creates a lowercase string that is suitable for case insensitive comparisons. This is more aggressive
than str.lower and may modify strings that are already in lowercase or cause strings to grow in length, and is not
intended for display purposes.
"XßΣ".casefold()
# 'xssσ'
"XßΣ".lower()
# 'xßς'
The transformations that take place under casefolding are defined by the Unicode Consortium in the
CaseFolding.txt file on their website.
str.upper()
str.upper takes every character in a string and converts it to its uppercase equivalent, for example:
"This is a 'string'.".upper()
# "THIS IS A 'STRING'."
str.lower()
str.lower does the opposite; it takes every character in a string and converts it to its lowercase equivalent:
"This IS a 'string'.".lower()
# "this is a 'string'."
str.capitalize()
str.capitalize returns a capitalized version of the string, that is, it makes the first character have upper case and
the rest lower:
"this Is A 'String'.".capitalize() # Capitalizes the first character and lowercases all others
# "This is a 'string'."
str.title()
str.title returns the title cased version of the string, that is, every letter in the beginning of a word is made upper
case and all others are made lower case:
str.swapcase returns a new string object in which all lower case characters are swapped to upper case and all
upper case characters to lower:
It is worth noting that these methods may be called either on string objects (as shown above) or as a class method
of the str class (with an explicit call to str.upper, etc.)
str.upper("This is a 'string'")
# "THIS IS A 'STRING'"
This is most useful when applying one of these methods to many strings at once in say, a map function.
map(str.upper,["These","are","some","'strings'"])
# ['THESE', 'ARE', 'SOME', "'STRINGS'"]
str.translate(table[, deletechars])
Parameter Description
table It is a lookup table that defines the mapping from one character to another.
deletechars A list of characters which are to be removed from the string.
The maketrans method (str.maketrans in Python 3 and string.maketrans in Python 2) allows you to generate a
translation table.
The translate method returns a string which is a translated copy of the original string.
You can set the table argument to None if you only need to delete characters.
>>> "{i:d} {f:0.1f} {s} {l!r} {d!r}".format(i=i, f=f, s=s, l=l, d=d)
For reference, Python also supports C-style qualifiers for string formatting. The examples below are equivalent to
those above, but the str.format versions are preferred due to benefits in flexibility, consistency of notation, and
extensibility:
"%(i)d %(f)0.1f %(s)s %(l)r %(d)r" % dict(i=i, f=f, s=s, l=l, d=d)
The braces uses for interpolation in str.format can also be numbered to reduce duplication when formatting
strings. For example, the following are equivalent:
While the official python documentation is, as usual, thorough enough, pyformat.info has a great set of examples
with detailed explanations.
See String Formatting for additional information. str.format() was proposed in PEP 3101 and f-strings in PEP 498.
string.ascii_letters:
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase:
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits:
>>> string.digits
'0123456789'
string.hexdigits:
>>> string.hexdigits
'0123456789abcdefABCDEF'
string.octaldigits:
>>> string.octaldigits
'01234567'
string.punctuation:
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
string.whitespace:
>>> string.whitespace
' \t\n\r\x0b\x0c'
In script mode, print(string.whitespace) will print the actual characters, use str to get the string returned
above.
string.printable:
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
\t\n\r\x0b\x0c'
str.strip([chars])
str.strip acts on a given string and removes (strips) any leading or trailing characters contained in the argument
chars; if chars is not supplied or is None, all white space characters are removed by default. For example:
If chars is supplied, all characters contained in it are removed from the string, which is returned. For example:
>>> ">>> a Python prompt".strip('> ') # strips '>' character and space character
'a Python prompt'
These methods have similar semantics and arguments with str.strip(), their difference lies in the direction from
which they start. str.rstrip() starts from the end of the string while str.lstrip() splits from the start of the
string.
>>> reversed('hello')
<reversed object at 0x0000000000000000>
>>> [char for char in reversed('hello')]
['o', 'l', 'l', 'e', 'h']
reversed() can be wrapped in a call to ''.join() to make a string from the iterator.
While using reversed() might be more readable to uninitiated Python users, using extended slicing with a step of
-1 is faster and more concise. Here , try to implement it as function:
str.split takes a string and returns a list of substrings of the original string. The behavior differs depending on
whether the sep argument is provided or omitted.
If sep isn't provided, or is None, then the splitting takes place wherever there is whitespace. However, leading and
trailing whitespace is ignored, and multiple consecutive whitespace characters are treated the same as a single
whitespace character:
The sep parameter can be used to define a delimiter string. The original string is split where the delimiter string
occurs, and the delimiter itself is discarded. Multiple consecutive delimiters are not treated the same as a single
occurrence, but rather cause empty strings to be created.
>>> "Earth,Stars,Sun,Moon".split(',')
['Earth', 'Stars', 'Sun', 'Moon']
The default is to split on every occurrence of the delimiter, however the maxsplit parameter limits the number of
splittings that occur. The default value of -1 means no limit:
str.rsplit ("right split") differs from str.split ("left split") when maxsplit is specified. The splitting starts at the
end of the string rather than at the beginning:
Note: Python specifies the maximum number of splits performed, while most other programming languages
specify the maximum number of substrings created. This may create confusion when porting or comparing code.
str.replace takes two arguments old and new containing the old sub-string which is to be replaced by the new sub-
string. The optional argument count specifies the number of replacements to be made:
For example, in order to replace 'foo' with 'spam' in the following string, we can call str.replace with old =
'foo' and new = 'spam':
If the given string contains multiple examples that match the old argument, all occurrences are replaced with the
value supplied in new:
>>> "It can foo multiple examples of foo if you want.".replace('foo', 'spam')
"It can spam multiple examples of spam if you want."
unless, of course, we supply a value for count. In this case count occurrences are going to get replaced:
str.isalpha
str.isalpha takes no arguments and returns True if the all characters in a given string are alphabetic, for example:
As an edge case, the empty string evaluates to False when used with "".isalpha().
str.isupper is a method that returns True if all characters in a given string are uppercase and False otherwise.
Conversely, str.islower is a method that returns True if all characters in a given string are lowercase and False
otherwise.
str.istitle returns True if the given string is title cased; that is, every word begins with an uppercase character
followed by lowercase characters.
str.isdecimal returns whether the string is a sequence of decimal digits, suitable for representing a decimal
number.
str.isdigit includes digits not in a form suitable for representing a decimal number, such as superscript digits.
Bytestrings (bytes in Python 3, str in Python 2), only support isdigit, which only checks for basic ASCII digits.
str.isalnum
This is a combination of str.isalpha and str.isnumeric, specifically it evaluates to True if all characters in the
given string are alphanumeric, that is, they consist of alphabetic or numeric characters:
>>> "Hello2World".isalnum()
True
>>> "HelloWorld".isalnum()
True
>>> "2016".isalnum()
True
>>> "Hello World".isalnum() # contains whitespace
False
str.isspace
>>> "\t\r\n".isspace()
True
>>> " ".isspace()
True
Sometimes a string looks “empty” but we don't know whether it's because it contains just whitespace or no
character at all
>>> "".isspace()
False
But the shortest way to test if a string is empty or just contains whitespace characters is to use strip(with no
arguments it removes all leading and trailing whitespace characters)
The following example separates the string elements with three hyphens.
str.count returns an int indicating the number of non-overlapping occurrences of the sub-string sub in another
string. The optional arguments start and end indicate the beginning and the end in which the search will take
place. By default start = 0 and end = len(str) meaning the whole string will be searched:
By specifying a different value for start, end we can get a more localized search and count, for example, if start is
equal to 13 the call to:
is equivalent to:
>>> t = s[start:]
The first thing to note it that case-removing conversions in unicode aren't trivial. There is text for which
text.lower() != text.upper().lower(), such as "ß":
>>> "ß".lower()
'ß'
>>> "ß".upper().lower()
'ss'
But let's say you wanted to caselessly compare "BUSSE" and "Buße". You probably also want to compare "BUSSE"
and "BUẞE" equal - that's the newer capital form. The recommended way is to use casefold:
>>> help(str.casefold)
"""
Help on method_descriptor:
casefold(...)
S.casefold() -> str
Do not just use lower. If casefold is not available, doing .upper().lower() helps (but only somewhat).
Then you should consider accents. If your font renderer is good, you probably think "ê" == "ê" - but it doesn't:
The simplest way to deal with this is unicodedata.normalize. You probably want to use NFKD normalization, but
feel free to check the documentation. Then one does
def normalize_caseless(text):
return unicodedata.normalize("NFKD", text.casefold())
interstates_lengths = {
5: (1381, 2222),
19: (63, 102),
40: (2555, 4112),
93: (189,305),
}
for road, length in interstates_lengths.items():
miles,kms = length
print('{} -> {} mi. ({} km.)'.format(str(road).rjust(4), str(miles).ljust(4),
str(kms).ljust(4)))
ljust and rjust are very similar. Both have a width parameter and an optional fillchar parameter. Any string
created by these functions is at least as long as the width parameter that was passed into the function. If the string
is longer than width alread, it is not truncated. The fillchar argument, which defaults to the space character ' '
must be a single character, not a multicharacter string.
The ljust function pads the end of the string it is called on with the fillchar until it is width characters long. The
rjust function pads the beginning of the string in a similar fashion. Therefore, the l and r in the names of these
functions refer to the side that the original string, not the fillchar, is positioned in the output string.
As it's name implies, str.startswith is used to test whether a given string starts with the given characters in
prefix.
>>> s.startswith("is", 2)
True
You can also use a tuple to check if it starts with any of a set of strings
str.endswith is exactly similar to str.startswith with the only difference being that it searches for ending
characters and not starting characters. For example, to test if a string ends in a full stop, one could write:
as with startswith more than one characters can used as the ending sequence:
>>> s.endswith('stop.')
True
>>> s.endswith('Stop.')
False
You can also use a tuple to check if it ends with any of a set of strings
In Python 2, you may need to convert str data to Unicode characters. The default ('', "", etc.) is an ASCII string, with
any values outside of ASCII range displayed as escaped values. Unicode strings are u'' (or u"", etc.).
# You get "© abc" encoded in UTF-8 from a file, network, or other data source
In Python 3 you may need to convert arrays of bytes (referred to as a 'byte literal') to strings of Unicode characters.
The default is now a Unicode string, and bytestring literals must now be entered as b'', b"", etc. A byte literal will
return True to isinstance(some_val, byte), assuming some_val to be a string that might be encoded as bytes.
You can use str.format to format output. Bracket pairs are replaced with arguments in the order in which the
arguments are passed:
Indexes can also be specified inside the brackets. The numbers correspond to indexes of the arguments passed to
the str.format function (0-based).
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('My value is: {0.value}'.format(my_value)) # "0" is optional
# Out: "My value is: 6"
Note: In addition to str.format, Python also provides the modulo operator %--also known as the string
formatting or interpolation operator (see PEP 3101)--for formatting strings. str.format is a successor of %
In addition to argument indexes, you can also include a format specification inside the curly brackets. This is an
expression that follows special rules and must be preceded by a colon (:). See the docs for a full description of
format specification. An example of format specification is the alignment directive :~^20 (^ stands for center
alignment, total width 20, fill with ~ character):
'{:~^20}'.format('centered')
# Out: '~~~~~~centered~~~~~~'
format allows behaviour not possible with %, for example repetition of arguments:
number_list = [12,45,78]
print map('the number is {}'.format, number_list)
# Out: ['the number is 12', 'the number is 45', 'the number is 78']
The format() method can be used to change the alignment of the string. You have to do it with a format expression
of the form :[fill_char][align_operator][width] where align_operator is one of:
fill_char (if omitted default is whitespace) is the character used for the padding.
'{:~<9s}, World'.format('Hello')
# 'Hello~~~~, World'
'{:~>9s}, World'.format('Hello')
# '~~~~Hello, World'
'{:0=6d}'.format(-123)
# '-00123'
Note: you could achieve the same results using the string functions ljust(), rjust(), center(), zfill(), however
these functions are deprecated since version 2.5.
This works with more advanced format strings too, including alignment and dot notation.
>>> f'{foo:^7s}'
' bar '
Note: The f'' does not denote a particular type like b'' for bytes or u'' for unicode in python2. The formating is
immediately applied, resulting in a normal stirng.
The expressions in an f-string are evaluated in left-to-right order. This is detectable only if the expressions have side
effects:
>>> '{0:.1f}'.format(42.12345)
'42.1'
>>> '{0:.3f}'.format(42.12345)
>>> '{0:.5f}'.format(42.12345)
'42.12345'
>>> '{0:.7f}'.format(42.12345)
'42.1234500'
>>> '{:.3f}'.format(42.12345)
'42.123'
>>> '{answer:.3f}'.format(answer=42.12345)
'42.123'
>>> '{0:.3e}'.format(42.12345)
'4.212e+01'
>>> '{0:.0%}'.format(42.12345)
'4212%'
You can also combine the {0} and {name} notations. This is especially useful when you want to round all variables
to a pre-specified number of decimals with 1 declaration:
>>> s = 'Hello'
>>> a, b, c = 1.12345, 2.34567, 34.5678
>>> digits = 2
str.format_map allows to use dictionaries without having to unpack them first. Also the class of data (which might
be a custom type) is used instead of a newly filled dict.
Without a dictionary:
>>> '{first} {last}'.format(first='Hodor', last='Hodor!')
'Hodor Hodor!'
A full list of list of datetime formatters can be found in the official documenttion.
>>> '8 bit: {0:08b}; Three bytes: {0:06x}'.format(42) # Add zero padding
'8 bit: 00101010; Three bytes: 00002a'
>>> '{:x}'.format(42.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'x' for object of type 'float'
>>> '{:.>10}'.format('foo')
'.......foo'
Those can also be provided as parameters to format by nesting more {} inside the {}:
In the latter example, the format string '{:{}{}{}}' is modified to '{:*^15}' (i.e. "center and pad with * to total
length of 15") before applying it to the actual string 'foo' to be formatted that way.
This can be useful in cases when parameters are not known beforehand, for instances when aligning tabular data:
class Person(object):
first = 'Zaphod'
last = 'Beeblebrox'
'{p.first} {p.last}'.format(p=Person())
# 'Zaphod Beeblebrox'
s = """
pad
{{:3}} :{a:3}:
truncate
combined
{{:>3.3}} :{a:>3.3}:
{{:3.3}} :{a:3.3}:
{{:3.3}} :{c:3.3}:
{{:3.3}} :{e:3.3}:
"""
Output:
pad
{:3} :1 :
truncate
{:.3} :555:
combined
{:>3.3} : 1:
{:3.3} :1 :
{:3.3} :333:
{:3.3} :555:
Everything below applies to the str.format method, as well as the format function. In the text below, the
two are interchangeable.
For every value which is passed to the format function, Python looks for a __format__ method for that argument.
Your own custom class can therefore have their own __format__ method to determine how the format function will
display and format your class and it's attributes.
This is different than the __str__ method, as in the __format__ method you can take into account the formatting
language, including alignment, field width etc, and even (if you wish) implement your own format specifiers, and
your own formatting language extensions.1
object.__format__(self, format_spec)
For example :
class Example(object):
def __init__(self,a,b,c):
self.a, self.b, self.c = a,b,c
inst = Example(1,2,3)
print "{0:>20s}".format( inst )
# out : (1,2,3)
# Note how the right align and field width of 20 has been honored.
Note:
If your custom class does not have a custom __format__ method and an instance of the class is passed to
the format function, Python2 will always use the return value of the __str__ method or __repr__
method to determine what to print (and if neither exist then the default repr will be used), and you will
need to use the s format specifier to format this. With Python3, to pass your custom class to the format
function, you will need define __format__ method on your custom class.
The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may
lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).
Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first
and then the effects).
n = 5
The result of this expression will be as it is read in English - if the conditional expression is True, then it will evaluate
to the expression on the left side, otherwise, the right side.
n = 5
"Hello" if n > 10 else "Goodbye" if n > 5 else "Good day"
number = 5
if number > 2:
print("Number is bigger than 2.")
elif number < 2: # Optional clause (you can have multiple elifs)
print("Number is smaller than 2.")
else: # Optional clause (you can only have one else)
print("Number is 2.")
Using else if instead of elif will trigger a syntax error and is not allowed.
Note: A common mistake is to simply check for the Falseness of an operation which returns different Falsey values
where the difference matters. For example, using if foo() rather than the more explicit if foo() is None
And operator
The and operator evaluates all expressions and returns the last expression if all expressions evaluate to True.
Otherwise it returns the first value that evaluates to False:
>>> 1 and 2
2
>>> 1 and 0
0
Or operator
The or operator evaluates the expressions left to right and returns the first value that evaluates to True or the last
value (if none are True).
>>> 1 or 2
1
>>> None or 1
1
>>> 0 or []
[]
Lazy evaluation
When you use this approach, remember that the evaluation is lazy. Expressions that are not required to be
evaluated to determine the result are not evaluated. For example:
In the above example, print_me is never executed because Python can determine the entire expression is False
when it encounters the 0 (False). Keep this in mind if print_me needs to execute to serve your program logic.
A common mistake when checking for multiple conditions is to apply the logic incorrectly.
This example is trying to check if two variables are each greater than 2. The statement is evaluated as - if (a) and
(b > 2). This produces an unexpected result because bool(a) evaluates as True when a is not zero.
>>> a = 1
>>> b = 6
>>> if a and b > 2:
... print('yes')
... else:
... print('no')
yes
no
Another, similar, mistake is made when checking if a variable is one of multiple values. The statement in this
example is evaluated as - if (a == 3) or (4) or (6). This produces an unexpected result because bool(4) and
bool(6) each evaluate to True
>>> a = 1
>>> if a == 3 or 4 or 6:
... print('yes')
... else:
... print('no')
yes
>>> if a == 3 or a == 4 or a == 6:
... print('yes')
... else:
... print('no')
no
Suppose you need to print 'greater than' if x > y, 'less than' if x < y and 'equal' if x == y.
Comparison Result
x<y -1
x == y 0
x>y 1
This function is removed on Python 3. You can use the cmp_to_key(func) helper function located in functools in
Python 3 to convert old comparison functions to key functions.
The else statement will execute it's body only if preceding conditional statements all evaluate to False.
if True:
print "It is true!"
else:
print "This won't get printed.."
# Output: It is true!
if False:
print "This won't get printed.."
else:
print "It is false!"
# Output: It is false!
if aDate is None:
But this can be optimized slightly by exploiting the notion that not None will evaluate to True in a boolean
expression. The following code is equivalent:
if not aDate:
aDate=datetime.date.today()
But there is a more Pythonic way. The following code is also equivalent:
aDate=aDate or datetime.date.today()
This does a Short Circuit evaluation. If aDate is initialized and is not None, then it gets assigned to itself with no net
effect. If it is None, then the datetime.date.today() gets assigned to aDate.
The if statements checks the condition. If it evaluates to True, it executes the body of the if statement. If it
evaluates to False, it skips the body.
if True:
print "It is true!"
>> It is true!
if False:
print "This won't get printed.."
if 2 + 2 == 4:
print "I know math!"
>> I know math!
As one of the most basic functions in programming, loops are an important piece to nearly every programming
language. Loops enable developers to set certain portions of their code to repeat through a number of loops which
are referred to as iterations. This topic covers using multiple types of loops and applications of loops in Python.
When a break statement executes inside a loop, control flow "breaks" out of the loop immediately:
i = 0
while i < 7:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1
The loop conditional will not be evaluated after the break statement is executed. Note that break statements are
only allowed inside loops, syntactically. A break statement inside a function cannot be used to terminate loops that
called that function.
Executing the following prints every digit until number 4 when the break statement is met and the loop stops:
0
1
2
3
4
Breaking from loop
break statements can also be used inside for loops, the other looping construct provided by Python:
0
1
2
Note that 3 and 4 are not printed since the loop has ended.
If a loop has an else clause, it does not execute when the loop is terminated through a break statement.
A continue statement will skip to the next iteration of the loop bypassing the rest of the current block but
continuing the loop. As with break, continue can only appear inside loops:
0
1
3
5
Note that 2 and 4 aren't printed, this is because continue goes to the next iteration instead of continuing on to
print(i) when i == 2 or i == 4.
Nested Loops
break and continue only operate on a single level of loop. The following example will only break out of the inner
for loop, not the outer while loop:
while True:
for i in range(1,5):
if i == 2:
break # Will only break out of the inner loop!
Python doesn't have the ability to break out of multiple levels of loop at once -- if this behavior is desired,
refactoring one or more loops into a function and replacing break with return may be the way to go.
The return statement exits from a function, without executing the code that comes after it.
If you have a loop inside a function, using return from inside that loop is equivalent to having a break as the rest of
the code of the loop is not executed (note that any code after the loop is not executed either):
def break_loop():
for i in range(1, 5):
if (i == 2):
return(i)
print(i)
return(5)
If you have nested loops, the return statement will break all loops:
def break_all():
for j in range(1, 5):
for i in range(1,4):
if i*j == 6:
return(i)
print(i*j)
will output:
1 # 1*1
Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, etc. The output
will be as follow:
0
1
2
3
4
range is a function that returns a series of numbers under an iterable form, thus it can be used in for loops:
for i in range(5):
print(i)
gives the exact same result as the first for loop. Note that 5 is not printed as the range here is the first five
numbers counting from 0.
for loop can iterate on any iterable object which is an object which defines a __getitem__ or a __iter__ function.
The __iter__ function returns an iterator, which is an object with a next function that is used to access the next
element of the iterable.
one
two
three
four
The range function generates numbers which are also often used in a for loop.
The result will be a special range sequence type in python >=3 and a list in python <=2. Both can be looped through
using the for loop.
1
2
3
4
5
If you want to loop though both the elements of a list and have an index for the elements as well, you can use
Python's enumerate function:
enumerate will generate tuples, which are unpacked into index (an integer) and item (the actual value from the list).
The above loop will print
Iterate over a list with value manipulation using map and lambda, i.e. apply lambda function on each element in the
list:
Output:
NB: in Python 3.x map returns an iterator instead of a list so you in case you need a list you have to cast the result
print(list(x)) (see
http://stackoverflow.com/documentation/python/809/incompatibilities-between-python-2-and-python-3/8186/map
) in http://stackoverflow.com/documentation/python/809/incompatibilities-between-python-2-and-python-3 ).
The else clause only executes after a for loop terminates by iterating to completion, or after a while loop
terminates by its conditional expression becoming false.
for i in range(3):
print(i)
else:
print('done')
i = 0
output:
0
1
2
done
The else clause does not execute if the loop terminates some other way (through a break statement or by raising
an exception):
for i in range(2):
print(i)
if i == 1:
break
else:
print('done')
output:
0
1
Most other programming languages lack this optional else clause of loops. The use of the keyword else in
particular is often considered confusing.
The original concept for such a clause dates back to Donald Knuth and the meaning of the else keyword becomes
clear if we rewrite a loop in terms of if statements and goto statements from earlier days before structured
programming or from a lower-level assembly language.
For example:
while loop_condition():
...
if break_condition():
break
...
is equivalent to:
# pseudocode
<<start>>:
if loop_condition():
...
if break_condition():
goto <<end>>
...
goto <<start>>
<<end>>:
For example:
while loop_condition():
...
if break_condition():
break
...
else:
print('done')
is equivalent to:
# pseudocode
<<start>>:
if loop_condition():
...
if break_condition():
goto <<end>>
...
goto <<start>>
else:
print('done')
<<end>>:
A for loop with an else clause can be understood the same way. Conceptually, there is a loop condition that
remains True as long as the iterable object or sequence still has some remaining elements.
The main use case for the for...else construct is a concise implementation of search as for instance:
a = [1, 2, 3, 4]
for i in a:
if type(i) is not int:
print(i)
break
else:
print("no exception")
To make the else in this construct less confusing one can think of it as "if not break" or "if not found".
Some discussions on this can be found in [Python-ideas] Summary of for...else threads, Why does python use 'else'
after for and while loops? , and Else Clauses on Loop Statements
for x in range(10):
pass #we don't want to do anything, or are not ready to do anything here, so we'll pass