Python Professional PDF
Python Professional PDF
Python
Notes for Professionals
®
800+ 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 ..................................................................................................................................... 10
Section 1.4: Datatypes ................................................................................................................................................. 11
Section 1.5: Collection Types ...................................................................................................................................... 15
Section 1.6: IDLE - Python GUI .................................................................................................................................... 19
Section 1.7: User Input ................................................................................................................................................. 21
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 ............................................................................................................................................... 31
Chapter 2: Python Data Types ............................................................................................................................ 33
Section 2.1: String Data Type ..................................................................................................................................... 33
Section 2.2: Set Data Types ....................................................................................................................................... 33
Section 2.3: Numbers data type ................................................................................................................................ 33
Section 2.4: List Data Type ......................................................................................................................................... 34
Section 2.5: Dictionary Data Type ............................................................................................................................. 34
Section 2.6: Tuple Data Type ..................................................................................................................................... 34
Chapter 3: Indentation ............................................................................................................................................. 35
Section 3.1: Simple example ....................................................................................................................................... 35
Section 3.2: How Indentation is Parsed ..................................................................................................................... 35
Section 3.3: Indentation Errors ................................................................................................................................... 36
Chapter 4: Comments and Documentation .................................................................................................. 37
Section 4.1: Single line, inline and multiline comments ............................................................................................ 37
Section 4.2: Programmatically accessing docstrings .............................................................................................. 37
Section 4.3: Write documentation using docstrings ................................................................................................ 38
Chapter 5: Date and Time ...................................................................................................................................... 42
Section 5.1: Parsing a string into a timezone aware datetime object .................................................................... 42
Section 5.2: Constructing timezone-aware datetimes ............................................................................................ 42
Section 5.3: Computing time dierences .................................................................................................................. 44
Section 5.4: Basic datetime objects usage ............................................................................................................... 44
Section 5.5: Switching between time zones .............................................................................................................. 45
Section 5.6: Simple date arithmetic ........................................................................................................................... 45
Section 5.7: Converting timestamp to datetime ...................................................................................................... 46
Section 5.8: Subtracting months from a date accurately ....................................................................................... 46
Section 5.9: Parsing an arbitrary ISO 8601 timestamp with minimal libraries ...................................................... 46
Section 5.10: Get an ISO 8601 timestamp .................................................................................................................. 47
Section 5.11: Parsing a string with a short time zone name into a timezone aware datetime object ................ 47
Section 5.12: Fuzzy datetime parsing (extracting datetime out of a text) ............................................................ 48
Section 5.13: Iterate over dates .................................................................................................................................. 49
Chapter 6: Date Formatting .................................................................................................................................. 50
Section 6.1: Time between two date-times ............................................................................................................... 50
Section 6.2: Outputting datetime object to string .................................................................................................... 50
Section 6.3: Parsing string to datetime object ......................................................................................................... 50
Chapter 7: Enum .......................................................................................................................................................... 51
Section 7.1: Creating an enum (Python 2.4 through 3.3) ......................................................................................... 51
Section 7.2: Iteration ................................................................................................................................................... 51
Chapter 8: Set ............................................................................................................................................................... 52
Section 8.1: Operations on sets .................................................................................................................................. 52
Section 8.2: Get the unique elements of a list .......................................................................................................... 53
Section 8.3: Set of Sets ................................................................................................................................................ 53
Section 8.4: Set Operations using Methods and Builtins ......................................................................................... 53
Section 8.5: Sets versus multisets .............................................................................................................................. 55
Chapter 9: Simple Mathematical Operators ................................................................................................. 57
Section 9.1: Division ..................................................................................................................................................... 57
Section 9.2: Addition .................................................................................................................................................... 58
Section 9.3: Exponentiation ........................................................................................................................................ 59
Section 9.4: Trigonometric Functions ........................................................................................................................ 60
Section 9.5: Inplace Operations ................................................................................................................................. 61
Section 9.6: Subtraction .............................................................................................................................................. 61
Section 9.7: Multiplication ........................................................................................................................................... 61
Section 9.8: Logarithms .............................................................................................................................................. 62
Section 9.9: Modulus ................................................................................................................................................... 62
Chapter 10: Bitwise Operators ............................................................................................................................. 65
Section 10.1: Bitwise NOT ............................................................................................................................................ 65
Section 10.2: Bitwise XOR (Exclusive OR) .................................................................................................................. 66
Section 10.3: Bitwise AND ............................................................................................................................................ 67
Section 10.4: Bitwise OR .............................................................................................................................................. 67
Section 10.5: Bitwise Left Shift .................................................................................................................................... 67
Section 10.6: Bitwise Right Shift .................................................................................................................................. 68
Section 10.7: Inplace Operations ................................................................................................................................ 68
Chapter 11: Boolean Operators ............................................................................................................................ 69
Section 11.1: `and` and `or` are not guaranteed to return a boolean ...................................................................... 69
Section 11.2: A simple example ................................................................................................................................... 69
Section 11.3: Short-circuit evaluation ......................................................................................................................... 69
Section 11.4: and ........................................................................................................................................................... 70
Section 11.5: or .............................................................................................................................................................. 70
Section 11.6: not ............................................................................................................................................................ 71
Chapter 12: Operator Precedence ...................................................................................................................... 72
Section 12.1: Simple Operator Precedence Examples in python ............................................................................. 72
Chapter 13: Variable Scope and Binding ......................................................................................................... 73
Section 13.1: Nonlocal Variables ................................................................................................................................. 73
Section 13.2: Global Variables .................................................................................................................................... 73
Section 13.3: Local Variables ...................................................................................................................................... 74
Section 13.4: The del command ................................................................................................................................. 75
Section 13.5: Functions skip class scope when looking up names ......................................................................... 76
Section 13.6: Local vs Global Scope ........................................................................................................................... 77
Section 13.7: Binding Occurrence ............................................................................................................................... 79
Chapter 14: Conditionals ......................................................................................................................................... 80
Section 14.1: Conditional Expression (or "The Ternary Operator") ......................................................................... 80
Section 14.2: if, elif, and else ....................................................................................................................................... 80
Section 14.3: Truth Values ........................................................................................................................................... 80
Section 14.4: Boolean Logic Expressions ................................................................................................................... 81
Section 14.5: Using the cmp function to get the comparison result of two objects ............................................. 83
Section 14.6: Else statement ....................................................................................................................................... 83
Section 14.7: Testing if an object is None and assigning it ...................................................................................... 84
Section 14.8: If statement ............................................................................................................................................ 84
Chapter 15: Comparisons ........................................................................................................................................ 86
Section 15.1: Chain Comparisons ................................................................................................................................ 86
Section 15.2: Comparison by `is` vs `==` ...................................................................................................................... 87
Section 15.3: Greater than or less than ...................................................................................................................... 88
Section 15.4: Not equal to ........................................................................................................................................... 88
Section 15.5: Equal To ................................................................................................................................................. 89
Section 15.6: Comparing Objects ............................................................................................................................... 89
Chapter 16: Loops ....................................................................................................................................................... 91
Section 16.1: Break and Continue in Loops ................................................................................................................ 91
Section 16.2: For loops ................................................................................................................................................ 93
Section 16.3: Iterating over lists .................................................................................................................................. 93
Section 16.4: Loops with an "else" clause .................................................................................................................. 94
Section 16.5: The Pass Statement .............................................................................................................................. 96
Section 16.6: Iterating over dictionaries .................................................................................................................... 97
Section 16.7: The "half loop" do-while ........................................................................................................................ 98
Section 16.8: Looping and Unpacking ....................................................................................................................... 98
Section 16.9: Iterating dierent portion of a list with dierent step size ............................................................... 99
Section 16.10: While Loop .......................................................................................................................................... 100
Chapter 17: Arrays .................................................................................................................................................... 102
Section 17.1: Access individual elements through indexes ..................................................................................... 102
Section 17.2: Basic Introduction to Arrays .............................................................................................................. 102
Section 17.3: Append any value to the array using append() method ................................................................ 103
Section 17.4: Insert value in an array using insert() method ................................................................................ 103
Section 17.5: Extend python array using extend() method ................................................................................... 103
Section 17.6: Add items from list into array using fromlist() method .................................................................. 104
Section 17.7: Remove any array element using remove() method ..................................................................... 104
Section 17.8: Remove last array element using pop() method ............................................................................ 104
Section 17.9: Fetch any element through its index using index() method ........................................................... 104
Section 17.10: Reverse a python array using reverse() method ........................................................................... 104
Section 17.11: Get array buer information through buer_info() method ........................................................ 105
Section 17.12: Check for number of occurrences of an element using count() method .................................... 105
Section 17.13: Convert array to string using tostring() method ............................................................................ 105
Section 17.14: Convert array to a python list with same elements using tolist() method .................................. 105
Section 17.15: Append a string to char array using fromstring() method ........................................................... 105
Chapter 18: Multidimensional arrays .............................................................................................................. 106
Section 18.1: Lists in lists ............................................................................................................................................ 106
Section 18.2: Lists in lists in lists in.. .......................................................................................................................... 106
Chapter 19: Dictionary ............................................................................................................................................ 108
Section 19.1: Introduction to Dictionary ................................................................................................................... 108
Section 19.2: Avoiding KeyError Exceptions ........................................................................................................... 109
Section 19.3: Iterating Over a Dictionary ................................................................................................................. 109
Section 19.4: Dictionary with default values ........................................................................................................... 110
Section 19.5: Merging dictionaries ........................................................................................................................... 111
Section 19.6: Accessing keys and values ................................................................................................................ 111
Section 19.7: Accessing values of a dictionary ....................................................................................................... 112
Section 19.8: Creating a dictionary .......................................................................................................................... 112
Section 19.9: Creating an ordered dictionary ......................................................................................................... 113
Section 19.10: Unpacking dictionaries using the ** operator ................................................................................. 113
Section 19.11: The trailing comma ............................................................................................................................ 114
Section 19.12: The dict() constructor ........................................................................................................................ 114
Section 19.13: Dictionaries Example ......................................................................................................................... 114
Section 19.14: All combinations of dictionary values .............................................................................................. 115
Chapter 20: List ......................................................................................................................................................... 117
Section 20.1: List methods and supported operators ............................................................................................ 117
Section 20.2: Accessing list values .......................................................................................................................... 122
Section 20.3: Checking if list is empty ..................................................................................................................... 123
Section 20.4: Iterating over a list ............................................................................................................................. 123
Section 20.5: Checking whether an item is in a list ................................................................................................ 124
Section 20.6: Any and All .......................................................................................................................................... 124
Section 20.7: Reversing list elements ...................................................................................................................... 125
Section 20.8: Concatenate and Merge lists ............................................................................................................ 125
Section 20.9: Length of a list .................................................................................................................................... 126
Section 20.10: Remove duplicate values in list ....................................................................................................... 126
Section 20.11: Comparison of lists ............................................................................................................................ 127
Section 20.12: Accessing values in nested list ........................................................................................................ 127
Section 20.13: Initializing a List to a Fixed Number of Elements ........................................................................... 128
Chapter 21: List comprehensions ...................................................................................................................... 130
Section 21.1: List Comprehensions ........................................................................................................................... 130
Section 21.2: Conditional List Comprehensions ...................................................................................................... 132
Section 21.3: Avoid repetitive and expensive operations using conditional clause ............................................ 134
Section 21.4: Dictionary Comprehensions ............................................................................................................... 135
Section 21.5: List Comprehensions with Nested Loops .......................................................................................... 136
Section 21.6: Generator Expressions ........................................................................................................................ 138
Section 21.7: Set Comprehensions ........................................................................................................................... 140
Section 21.8: Refactoring filter and map to list comprehensions ......................................................................... 140
Section 21.9: Comprehensions involving tuples ...................................................................................................... 141
Section 21.10: Counting Occurrences Using Comprehension ............................................................................... 142
Section 21.11: Changing Types in a List .................................................................................................................... 142
Section 21.12: Nested List Comprehensions ............................................................................................................ 142
Section 21.13: Iterate two or more list simultaneously within list comprehension .............................................. 143
Chapter 22: List slicing (selecting parts of lists) ....................................................................................... 144
Section 22.1: Using the third "step" argument ........................................................................................................ 144
Section 22.2: Selecting a sublist from a list ............................................................................................................ 144
Section 22.3: Reversing a list with slicing ................................................................................................................ 144
Section 22.4: Shifting a list using slicing .................................................................................................................. 144
Chapter 23: groupby() ............................................................................................................................................ 146
Section 23.1: Example 4 ............................................................................................................................................. 146
Section 23.2: Example 2 ............................................................................................................................................ 146
Section 23.3: Example 3 ............................................................................................................................................ 147
Chapter 24: Linked lists ......................................................................................................................................... 149
Section 24.1: Single linked list example ................................................................................................................... 149
Chapter 25: Linked List Node ............................................................................................................................. 154
Section 25.1: Write a simple Linked List Node in python ....................................................................................... 154
Chapter 26: Filter ...................................................................................................................................................... 155
Section 26.1: Basic use of filter ................................................................................................................................. 155
Section 26.2: Filter without function ........................................................................................................................ 155
Section 26.3: Filter as short-circuit check ............................................................................................................... 156
Section 26.4: Complementary function: filterfalse, ifilterfalse .............................................................................. 156
Chapter 27: Heapq ................................................................................................................................................... 158
Section 27.1: Largest and smallest items in a collection ....................................................................................... 158
Section 27.2: Smallest item in a collection .............................................................................................................. 158
Chapter 28: Tuple ..................................................................................................................................................... 160
Section 28.1: Tuple ..................................................................................................................................................... 160
Section 28.2: Tuples are immutable ........................................................................................................................ 161
Section 28.3: Packing and Unpacking Tuples ........................................................................................................ 161
Section 28.4: Built-in Tuple Functions ..................................................................................................................... 162
Section 28.5: Tuple Are Element-wise Hashable and Equatable ......................................................................... 163
Section 28.6: Indexing Tuples ................................................................................................................................... 164
Section 28.7: Reversing Elements ............................................................................................................................ 164
Chapter 29: Basic Input and Output ............................................................................................................... 165
Section 29.1: Using the print function ...................................................................................................................... 165
Section 29.2: Input from a File ................................................................................................................................. 165
Section 29.3: Read from stdin .................................................................................................................................. 167
Section 29.4: Using input() and raw_input() .......................................................................................................... 167
Section 29.5: Function to prompt user for a number ............................................................................................ 167
Section 29.6: Printing a string without a newline at the end ................................................................................. 168
Chapter 30: Files & Folders I/O ......................................................................................................................... 171
Section 30.1: File modes ............................................................................................................................................ 171
Section 30.2: Reading a file line-by-line .................................................................................................................. 172
Section 30.3: Iterate files (recursively) .................................................................................................................... 173
Section 30.4: Getting the full contents of a file ...................................................................................................... 173
Section 30.5: Writing to a file ................................................................................................................................... 174
Section 30.6: Check whether a file or path exists .................................................................................................. 175
Section 30.7: Random File Access Using mmap .................................................................................................... 176
Section 30.8: Replacing text in a file ....................................................................................................................... 176
Section 30.9: Checking if a file is empty ................................................................................................................. 176
Section 30.10: Read a file between a range of lines .............................................................................................. 177
Section 30.11: Copy a directory tree ........................................................................................................................ 177
Section 30.12: Copying contents of one file to a dierent file .............................................................................. 177
Chapter 31: os.path .................................................................................................................................................. 178
Section 31.1: Join Paths ............................................................................................................................................. 178
Section 31.2: Path Component Manipulation .......................................................................................................... 178
Section 31.3: Get the parent directory ..................................................................................................................... 178
Section 31.4: If the given path exists ........................................................................................................................ 178
Section 31.5: check if the given path is a directory, file, symbolic link, mount point etc .................................... 179
Section 31.6: Absolute Path from Relative Path ..................................................................................................... 179
Chapter 32: Iterables and Iterators ................................................................................................................ 180
Section 32.1: Iterator vs Iterable vs Generator ....................................................................................................... 180
Section 32.2: Extract values one by one ................................................................................................................. 181
Section 32.3: Iterating over entire iterable ............................................................................................................. 181
Section 32.4: Verify only one element in iterable .................................................................................................. 181
Section 32.5: What can be iterable .......................................................................................................................... 182
Section 32.6: Iterator isn't reentrant! ....................................................................................................................... 182
Chapter 33: Functions ............................................................................................................................................. 183
Section 33.1: Defining and calling simple functions ............................................................................................... 183
Section 33.2: Defining a function with an arbitrary number of arguments ........................................................ 184
Section 33.3: Lambda (Inline/Anonymous) Functions .......................................................................................... 187
Section 33.4: Defining a function with optional arguments .................................................................................. 189
Section 33.5: Defining a function with optional mutable arguments ................................................................... 190
Section 33.6: Argument passing and mutability .................................................................................................... 191
Section 33.7: Returning values from functions ....................................................................................................... 192
Section 33.8: Closure ................................................................................................................................................. 192
Section 33.9: Forcing the use of named parameters ............................................................................................ 193
Section 33.10: Nested functions ............................................................................................................................... 194
Section 33.11: Recursion limit .................................................................................................................................... 194
Section 33.12: Recursive Lambda using assigned variable ................................................................................... 195
Section 33.13: Recursive functions ........................................................................................................................... 195
Section 33.14: Defining a function with arguments ................................................................................................ 196
Section 33.15: Iterable and dictionary unpacking .................................................................................................. 196
Section 33.16: Defining a function with multiple arguments ................................................................................. 198
Chapter 34: Defining functions with list arguments .............................................................................. 199
Section 34.1: Function and Call ................................................................................................................................. 199
Chapter 35: Functional Programming in Python ...................................................................................... 201
Section 35.1: Lambda Function ................................................................................................................................ 201
Section 35.2: Map Function ...................................................................................................................................... 201
Section 35.3: Reduce Function ................................................................................................................................. 201
Section 35.4: Filter Function ..................................................................................................................................... 201
Chapter 36: Partial functions .............................................................................................................................. 202
Section 36.1: Raise the power ................................................................................................................................... 202
Chapter 37: Decorators ......................................................................................................................................... 203
Section 37.1: Decorator function .............................................................................................................................. 203
Section 37.2: Decorator class ................................................................................................................................... 204
Section 37.3: Decorator with arguments (decorator factory) .............................................................................. 205
Section 37.4: Making a decorator look like the decorated function .................................................................... 207
Section 37.5: Using a decorator to time a function ............................................................................................... 207
Section 37.6: Create singleton class with a decorator .......................................................................................... 208
Chapter 38: Classes ................................................................................................................................................. 209
Section 38.1: Introduction to classes ........................................................................................................................ 209
Section 38.2: Bound, unbound, and static methods .............................................................................................. 210
Section 38.3: Basic inheritance ................................................................................................................................ 212
Section 38.4: Monkey Patching ................................................................................................................................ 214
Section 38.5: New-style vs. old-style classes .......................................................................................................... 214
Section 38.6: Class methods: alternate initializers ................................................................................................. 215
Section 38.7: Multiple Inheritance ............................................................................................................................ 217
Section 38.8: Properties ............................................................................................................................................ 219
Section 38.9: Default values for instance variables ............................................................................................... 220
Section 38.10: Class and instance variables ........................................................................................................... 221
Section 38.11: Class composition .............................................................................................................................. 222
Section 38.12: Listing All Class Members ................................................................................................................. 223
Section 38.13: Singleton class ................................................................................................................................... 224
Section 38.14: Descriptors and Dotted Lookups .................................................................................................... 225
Chapter 39: Metaclasses ....................................................................................................................................... 226
Section 39.1: Basic Metaclasses ............................................................................................................................... 226
Section 39.2: Singletons using metaclasses ........................................................................................................... 227
Section 39.3: Using a metaclass .............................................................................................................................. 227
Section 39.4: Introduction to Metaclasses .............................................................................................................. 227
Section 39.5: Custom functionality with metaclasses ........................................................................................... 228
Section 39.6: The default metaclass ....................................................................................................................... 229
Chapter 40: String Formatting ......................................................................................................................... 232
Section 40.1: Basics of String Formatting ............................................................................................................... 232
Section 40.2: Alignment and padding ..................................................................................................................... 233
Section 40.3: Format literals (f-string) .................................................................................................................... 234
Section 40.4: Float formatting ................................................................................................................................. 234
Section 40.5: Named placeholders ......................................................................................................................... 235
Section 40.6: String formatting with datetime ....................................................................................................... 236
Section 40.7: Formatting Numerical Values ........................................................................................................... 236
Section 40.8: Nested formatting .............................................................................................................................. 237
Section 40.9: Format using Getitem and Getattr ................................................................................................... 237
Section 40.10: Padding and truncating strings, combined .................................................................................... 237
Section 40.11: Custom formatting for a class ......................................................................................................... 238
Chapter 41: String Methods ................................................................................................................................ 240
Section 41.1: Changing the capitalization of a string ............................................................................................. 240
Section 41.2: str.translate: Translating characters in a string ............................................................................... 241
Section 41.3: str.format and f-strings: Format values into a string ...................................................................... 242
Section 41.4: String module's useful constants ....................................................................................................... 243
Section 41.5: Stripping unwanted leading/trailing characters from a string ...................................................... 244
Section 41.6: Reversing a string ............................................................................................................................... 245
Section 41.7: Split a string based on a delimiter into a list of strings ................................................................... 245
Section 41.8: Replace all occurrences of one substring with another substring ................................................ 246
Section 41.9: Testing what a string is composed of ............................................................................................... 247
Section 41.10: String Contains ................................................................................................................................... 249
Section 41.11: Join a list of strings into one string ................................................................................................... 249
Section 41.12: Counting number of times a substring appears in a string .......................................................... 250
Section 41.13: Case insensitive string comparisons ................................................................................................ 250
Section 41.14: Justify strings ..................................................................................................................................... 251
Section 41.15: Test the starting and ending characters of a string ...................................................................... 252
Section 41.16: Conversion between str or bytes data and unicode characters .................................................. 253
Chapter 42: Using loops within functions .................................................................................................... 255
Section 42.1: Return statement inside loop in a function ...................................................................................... 255
Chapter 43: Importing modules ........................................................................................................................ 256
Section 43.1: Importing a module ............................................................................................................................ 256
Section 43.2: The __all__ special variable ............................................................................................................ 257
Section 43.3: Import modules from an arbitrary filesystem location .................................................................. 258
Section 43.4: Importing all names from a module ................................................................................................ 258
Section 43.5: Programmatic importing ................................................................................................................... 259
Section 43.6: PEP8 rules for Imports ....................................................................................................................... 259
Section 43.7: Importing specific names from a module ........................................................................................ 260
Section 43.8: Importing submodules ....................................................................................................................... 260
Section 43.9: Re-importing a module ...................................................................................................................... 260
Section 43.10: __import__() function ..................................................................................................................... 261
Chapter 44: Dierence between Module and Package ...................................................................... 262
Section 44.1: Modules ................................................................................................................................................ 262
Section 44.2: Packages ............................................................................................................................................. 262
Chapter 45: Math Module .................................................................................................................................... 264
Section 45.1: Rounding: round, floor, ceil, trunc ...................................................................................................... 264
Section 45.2: Trigonometry ...................................................................................................................................... 265
Section 45.3: Pow for faster exponentiation ........................................................................................................... 266
Section 45.4: Infinity and NaN ("not a number") ................................................................................................... 266
Section 45.5: Logarithms .......................................................................................................................................... 269
Section 45.6: Constants ............................................................................................................................................ 269
Section 45.7: Imaginary Numbers ........................................................................................................................... 270
Section 45.8: Copying signs ..................................................................................................................................... 270
Section 45.9: Complex numbers and the cmath module ...................................................................................... 270
Chapter 46: Complex math ................................................................................................................................. 273
Section 46.1: Advanced complex arithmetic ........................................................................................................... 273
Section 46.2: Basic complex arithmetic .................................................................................................................. 274
Chapter 47: Collections module ....................................................................................................................... 275
Section 47.1: collections.Counter .............................................................................................................................. 275
Section 47.2: collections.OrderedDict ...................................................................................................................... 276
Section 47.3: collections.defaultdict ......................................................................................................................... 277
Section 47.4: collections.namedtuple ...................................................................................................................... 278
Section 47.5: collections.deque ................................................................................................................................ 279
Section 47.6: collections.ChainMap .......................................................................................................................... 280
Chapter 48: Operator module ........................................................................................................................... 282
Section 48.1: Itemgetter ............................................................................................................................................ 282
Section 48.2: Operators as alternative to an infix operator ................................................................................. 282
Section 48.3: Methodcaller ....................................................................................................................................... 282
Chapter 49: JSON Module .................................................................................................................................... 284
Section 49.1: Storing data in a file ............................................................................................................................ 284
Section 49.2: Retrieving data from a file ................................................................................................................ 284
Section 49.3: Formatting JSON output ................................................................................................................... 284
Section 49.4: `load` vs `loads`, `dump` vs `dumps` ................................................................................................... 285
Section 49.5: Calling `json.tool` from the command line to pretty-print JSON output ...................................... 286
Section 49.6: JSON encoding custom objects ........................................................................................................ 286
Section 49.7: Creating JSON from Python dict ...................................................................................................... 287
Section 49.8: Creating Python dict from JSON ...................................................................................................... 287
Chapter 50: Sqlite3 Module ................................................................................................................................. 289
Section 50.1: Sqlite3 - Not require separate server process ................................................................................. 289
Section 50.2: Getting the values from the database and Error handling ........................................................... 289
Chapter 51: The os Module ................................................................................................................................... 291
Section 51.1: makedirs - recursive directory creation ............................................................................................ 291
Section 51.2: Create a directory ............................................................................................................................... 292
Section 51.3: Get current directory .......................................................................................................................... 292
Section 51.4: Determine the name of the operating system ................................................................................ 292
Section 51.5: Remove a directory ............................................................................................................................ 292
Section 51.6: Follow a symlink (POSIX) .................................................................................................................... 292
Section 51.7: Change permissions on a file ............................................................................................................. 292
Chapter 52: The locale Module .......................................................................................................................... 293
Section 52.1: Currency Formatting US Dollars Using the locale Module ............................................................. 293
Chapter 53: Itertools Module .............................................................................................................................. 294
Section 53.1: Combinations method in Itertools Module ....................................................................................... 294
Section 53.2: itertools.dropwhile .............................................................................................................................. 294
Section 53.3: Zipping two iterators until they are both exhausted ...................................................................... 295
Section 53.4: Take a slice of a generator ............................................................................................................... 295
Section 53.5: Grouping items from an iterable object using a function .............................................................. 296
Section 53.6: itertools.takewhile ............................................................................................................................... 297
Section 53.7: itertools.permutations ........................................................................................................................ 297
Section 53.8: itertools.repeat .................................................................................................................................... 298
Section 53.9: Get an accumulated sum of numbers in an iterable ...................................................................... 298
Section 53.10: Cycle through elements in an iterator ............................................................................................ 298
Section 53.11: itertools.product ................................................................................................................................. 298
Section 53.12: itertools.count .................................................................................................................................... 299
Section 53.13: Chaining multiple iterators together ............................................................................................... 300
Chapter 54: Asyncio Module ............................................................................................................................... 301
Section 54.1: Coroutine and Delegation Syntax ..................................................................................................... 301
Section 54.2: Asynchronous Executors ................................................................................................................... 302
Section 54.3: Using UVLoop ..................................................................................................................................... 303
Section 54.4: Synchronization Primitive: Event ....................................................................................................... 303
Section 54.5: A Simple Websocket .......................................................................................................................... 304
Section 54.6: Common Misconception about asyncio .......................................................................................... 304
Chapter 55: Random module ............................................................................................................................. 307
Section 55.1: Creating a random user password ................................................................................................... 307
Section 55.2: Create cryptographically secure random numbers ....................................................................... 307
Section 55.3: Random and sequences: shue, choice and sample .................................................................... 308
Section 55.4: Creating random integers and floats: randint, randrange, random, and uniform ...................... 309
Section 55.5: Reproducible random numbers: Seed and State ............................................................................ 310
Section 55.6: Random Binary Decision ................................................................................................................... 311
Chapter 56: Functools Module ........................................................................................................................... 312
Section 56.1: partial ................................................................................................................................................... 312
Section 56.2: cmp_to_key ....................................................................................................................................... 312
Section 56.3: lru_cache ............................................................................................................................................. 312
Section 56.4: total_ordering ..................................................................................................................................... 313
Section 56.5: reduce .................................................................................................................................................. 314
Chapter 57: The dis module ................................................................................................................................ 315
Section 57.1: What is Python bytecode? ................................................................................................................. 315
Section 57.2: Constants in the dis module .............................................................................................................. 315
Section 57.3: Disassembling modules ..................................................................................................................... 315
Chapter 58: The base64 Module ....................................................................................................................... 317
Section 58.1: Encoding and Decoding Base64 ....................................................................................................... 318
Section 58.2: Encoding and Decoding Base32 ....................................................................................................... 319
Section 58.3: Encoding and Decoding Base16 ........................................................................................................ 320
Section 58.4: Encoding and Decoding ASCII85 ...................................................................................................... 320
Section 58.5: Encoding and Decoding Base85 ....................................................................................................... 321
Chapter 59: Queue Module .................................................................................................................................. 322
Section 59.1: Simple example ................................................................................................................................... 322
Chapter 60: Deque Module .................................................................................................................................. 324
Section 60.1: Basic deque using ............................................................................................................................... 324
Section 60.2: Available methods in deque .............................................................................................................. 324
Section 60.3: limit deque size ................................................................................................................................... 325
Section 60.4: Breadth First Search .......................................................................................................................... 325
Chapter 61: Webbrowser Module ...................................................................................................................... 326
Section 61.1: Opening a URL with Default Browser ................................................................................................ 326
Section 61.2: Opening a URL with Dierent Browsers ........................................................................................... 327
Chapter 62: tkinter ................................................................................................................................................... 328
Section 62.1: Geometry Managers ........................................................................................................................... 328
Section 62.2: A minimal tkinter Application ............................................................................................................ 329
Chapter 63: pyautogui module .......................................................................................................................... 331
Section 63.1: Mouse Functions .................................................................................................................................. 331
Section 63.2: Keyboard Functions ........................................................................................................................... 331
Section 63.3: Screenshot And Image Recognition ................................................................................................. 331
Chapter 64: Indexing and Slicing ...................................................................................................................... 332
Section 64.1: Basic Slicing ......................................................................................................................................... 332
Section 64.2: Reversing an object ........................................................................................................................... 333
Section 64.3: Slice assignment ................................................................................................................................. 333
Section 64.4: Making a shallow copy of an array .................................................................................................. 333
Section 64.5: Indexing custom classes: __getitem__, __setitem__ and __delitem__ ................................... 334
Section 64.6: Basic Indexing ..................................................................................................................................... 335
Chapter 65: Plotting with Matplotlib .............................................................................................................. 337
Section 65.1: Plots with Common X-axis but dierent Y-axis : Using twinx() ....................................................... 337
Section 65.2: Plots with common Y-axis and dierent X-axis using twiny() ....................................................... 338
Section 65.3: A Simple Plot in Matplotlib ................................................................................................................. 340
Section 65.4: Adding more features to a simple plot : axis labels, title, axis ticks, grid, and legend ................ 341
Section 65.5: Making multiple plots in the same figure by superimposition similar to MATLAB ...................... 342
Section 65.6: Making multiple Plots in the same figure using plot superimposition with separate plot
commands ......................................................................................................................................................... 343
Chapter 66: graph-tool .......................................................................................................................................... 345
Section 66.1: PyDotPlus ............................................................................................................................................. 345
Section 66.2: PyGraphviz .......................................................................................................................................... 345
Chapter 67: Generators ......................................................................................................................................... 347
Section 67.1: Introduction .......................................................................................................................................... 347
Section 67.2: Infinite sequences ............................................................................................................................... 349
Section 67.3: Sending objects to a generator ........................................................................................................ 350
Section 67.4: Yielding all values from another iterable ......................................................................................... 351
Section 67.5: Iteration ............................................................................................................................................... 351
Section 67.6: The next() function ............................................................................................................................. 351
Section 67.7: Coroutines ........................................................................................................................................... 352
Section 67.8: Refactoring list-building code ........................................................................................................... 352
Section 67.9: Yield with recursion: recursively listing all files in a directory ........................................................ 353
Section 67.10: Generator expressions ...................................................................................................................... 354
Section 67.11: Using a generator to find Fibonacci Numbers ............................................................................... 354
Section 67.12: Searching ........................................................................................................................................... 354
Section 67.13: Iterating over generators in parallel ............................................................................................... 355
Chapter 68: Reduce ................................................................................................................................................. 356
Section 68.1: Overview .............................................................................................................................................. 356
Section 68.2: Using reduce ....................................................................................................................................... 356
Section 68.3: Cumulative product ............................................................................................................................ 357
Section 68.4: Non short-circuit variant of any/all ................................................................................................. 357
Chapter 69: Map Function .................................................................................................................................... 358
Section 69.1: Basic use of map, itertools.imap and future_builtins.map ............................................................. 358
Section 69.2: Mapping each value in an iterable ................................................................................................... 358
Section 69.3: Mapping values of dierent iterables .............................................................................................. 359
Section 69.4: Transposing with Map: Using "None" as function argument (python 2.x only) .......................... 361
Section 69.5: Series and Parallel Mapping .............................................................................................................. 361
Chapter 70: Exponentiation ................................................................................................................................ 365
Section 70.1: Exponentiation using builtins: ** and pow() ...................................................................................... 365
Section 70.2: Square root: math.sqrt() and cmath.sqrt ......................................................................................... 365
Section 70.3: Modular exponentiation: pow() with 3 arguments .......................................................................... 366
Section 70.4: Computing large integer roots ......................................................................................................... 366
Section 70.5: Exponentiation using the math module: math.pow() ..................................................................... 367
Section 70.6: Exponential function: math.exp() and cmath.exp() ......................................................................... 368
Section 70.7: Exponential function minus 1: math.expm1() .................................................................................... 368
Section 70.8: Magic methods and exponentiation: builtin, math and cmath ...................................................... 369
Section 70.9: Roots: nth-root with fractional exponents ....................................................................................... 370
Chapter 71: Searching ............................................................................................................................................ 371
Section 71.1: Searching for an element .................................................................................................................... 371
Section 71.2: Searching in custom classes: __contains__ and __iter__ ........................................................... 371
Section 71.3: Getting the index for strings: str.index(), str.rindex() and str.find(), str.rfind() ............................... 372
Section 71.4: Getting the index list and tuples: list.index(), tuple.index() .............................................................. 373
Section 71.5: Searching key(s) for a value in dict ................................................................................................... 373
Section 71.6: Getting the index for sorted sequences: bisect.bisect_left() .......................................................... 374
Section 71.7: Searching nested sequences ............................................................................................................. 374
Chapter 72: Sorting, Minimum and Maximum ............................................................................................ 376
Section 72.1: Make custom classes orderable ........................................................................................................ 376
Section 72.2: Special case: dictionaries ................................................................................................................... 378
Section 72.3: Using the key argument .................................................................................................................... 379
Section 72.4: Default Argument to max, min ......................................................................................................... 379
Section 72.5: Getting a sorted sequence ................................................................................................................ 380
Section 72.6: Extracting N largest or N smallest items from an iterable ............................................................ 380
Section 72.7: Getting the minimum or maximum of several values .................................................................... 381
Section 72.8: Minimum and Maximum of a sequence ........................................................................................... 381
Chapter 73: Counting .............................................................................................................................................. 382
Section 73.1: Counting all occurrence of all items in an iterable: collections.Counter ........................................ 382
Section 73.2: Getting the most common value(-s): collections.Counter.most_common() ................................ 382
Section 73.3: Counting the occurrences of one item in a sequence: list.count() and tuple.count() .................. 382
Section 73.4: Counting the occurrences of a substring in a string: str.count() ................................................... 383
Section 73.5: Counting occurrences in numpy array ............................................................................................ 383
Chapter 74: The Print Function ......................................................................................................................... 384
Section 74.1: Print basics ........................................................................................................................................... 384
Section 74.2: Print parameters ................................................................................................................................ 385
Chapter 75: Regular Expressions (Regex) ................................................................................................... 388
Section 75.1: Matching the beginning of a string ................................................................................................... 388
Section 75.2: Searching ............................................................................................................................................ 389
Section 75.3: Precompiled patterns ......................................................................................................................... 389
Section 75.4: Flags .................................................................................................................................................... 390
Section 75.5: Replacing ............................................................................................................................................. 391
Section 75.6: Find All Non-Overlapping Matches ................................................................................................... 391
Section 75.7: Checking for allowed characters ...................................................................................................... 392
Section 75.8: Splitting a string using regular expressions ..................................................................................... 392
Section 75.9: Grouping .............................................................................................................................................. 392
Section 75.10: Escaping Special Characters ........................................................................................................... 393
Section 75.11: Match an expression only in specific locations ............................................................................... 394
Section 75.12: Iterating over matches using `re.finditer` ........................................................................................ 395
Chapter 76: Copying data .................................................................................................................................... 396
Section 76.1: Copy a dictionary ................................................................................................................................ 396
Section 76.2: Performing a shallow copy ............................................................................................................... 396
Section 76.3: Performing a deep copy .................................................................................................................... 396
Section 76.4: Performing a shallow copy of a list .................................................................................................. 396
Section 76.5: Copy a set ........................................................................................................................................... 396
Chapter 77: Context Managers (“with” Statement) ............................................................................... 398
Section 77.1: Introduction to context managers and the with statement ............................................................ 398
Section 77.2: Writing your own context manager ................................................................................................. 398
Section 77.3: Writing your own contextmanager using generator syntax ......................................................... 399
Section 77.4: Multiple context managers ................................................................................................................ 400
Section 77.5: Assigning to a target .......................................................................................................................... 400
Section 77.6: Manage Resources ............................................................................................................................. 401
Chapter 78: The __name__ special variable ........................................................................................... 402
Section 78.1: __name__ == '__main__' ................................................................................................................. 402
Section 78.2: Use in logging ..................................................................................................................................... 402
Section 78.3: function_class_or_module.__name__ .......................................................................................... 402
Chapter 79: Checking Path Existence and Permissions ......................................................................... 404
Section 79.1: Perform checks using os.access ........................................................................................................ 404
Chapter 80: Creating Python packages ....................................................................................................... 406
Section 80.1: Introduction ......................................................................................................................................... 406
Section 80.2: Uploading to PyPI .............................................................................................................................. 406
Section 80.3: Making package executable ............................................................................................................. 408
Chapter 81: Usage of "pip" module: PyPI Package Manager ............................................................. 410
Section 81.1: Example use of commands ................................................................................................................ 410
Section 81.2: Handling ImportError Exception ........................................................................................................ 410
Section 81.3: Force install .......................................................................................................................................... 411
Chapter 82: pip: PyPI Package Manager ...................................................................................................... 412
Section 82.1: Install Packages .................................................................................................................................. 412
Section 82.2: To list all packages installed using `pip` ........................................................................................... 412
Section 82.3: Upgrade Packages ............................................................................................................................ 412
Section 82.4: Uninstall Packages ............................................................................................................................. 413
Section 82.5: Updating all outdated packages on Linux ...................................................................................... 413
Section 82.6: Updating all outdated packages on Windows ................................................................................ 413
Section 82.7: Create a requirements.txt file of all packages on the system ....................................................... 413
Section 82.8: Using a certain Python version with pip .......................................................................................... 414
Section 82.9: Create a requirements.txt file of packages only in the current virtualenv .................................. 414
Section 82.10: Installing packages not yet on pip as wheels ................................................................................ 415
Chapter 83: Parsing Command Line arguments ...................................................................................... 418
Section 83.1: Hello world in argparse ...................................................................................................................... 418
Section 83.2: Using command line arguments with argv ..................................................................................... 418
Section 83.3: Setting mutually exclusive arguments with argparse .................................................................... 419
Section 83.4: Basic example with docopt ............................................................................................................... 420
Section 83.5: Custom parser error message with argparse ................................................................................. 420
Section 83.6: Conceptual grouping of arguments with argparse.add_argument_group() ............................. 421
Section 83.7: Advanced example with docopt and docopt_dispatch ................................................................. 422
Chapter 84: Subprocess Library ...................................................................................................................... 424
Section 84.1: More flexibility with Popen ................................................................................................................. 424
Section 84.2: Calling External Commands .............................................................................................................. 425
Section 84.3: How to create the command list argument .................................................................................... 425
Chapter 85: setup.py .............................................................................................................................................. 427
Section 85.1: Purpose of setup.py ............................................................................................................................ 427
Section 85.2: Using source control metadata in setup.py .................................................................................... 427
Section 85.3: Adding command line scripts to your python package ................................................................. 428
Section 85.4: Adding installation options ................................................................................................................ 428
Chapter 86: Recursion ............................................................................................................................................ 430
Section 86.1: The What, How, and When of Recursion .......................................................................................... 430
Section 86.2: Tree exploration with recursion ........................................................................................................ 433
Section 86.3: Sum of numbers from 1 to n .............................................................................................................. 434
Section 86.4: Increasing the Maximum Recursion Depth ...................................................................................... 434
Section 86.5: Tail Recursion - Bad Practice ............................................................................................................ 435
Section 86.6: Tail Recursion Optimization Through Stack Introspection ............................................................ 435
Chapter 87: Type Hints .......................................................................................................................................... 437
Section 87.1: Adding types to a function ................................................................................................................. 437
Section 87.2: NamedTuple ....................................................................................................................................... 438
Section 87.3: Generic Types ..................................................................................................................................... 438
Section 87.4: Variables and Attributes .................................................................................................................... 438
Section 87.5: Class Members and Methods ............................................................................................................ 439
Section 87.6: Type hints for keyword arguments .................................................................................................. 439
Chapter 88: Exceptions .......................................................................................................................................... 440
Section 88.1: Catching Exceptions ............................................................................................................................ 440
Section 88.2: Do not catch everything! ................................................................................................................... 440
Section 88.3: Re-raising exceptions ......................................................................................................................... 441
Section 88.4: Catching multiple exceptions ............................................................................................................ 441
Section 88.5: Exception Hierarchy ........................................................................................................................... 442
Section 88.6: Else ....................................................................................................................................................... 444
Section 88.7: Raising Exceptions .............................................................................................................................. 444
Section 88.8: Creating custom exception types ..................................................................................................... 445
Section 88.9: Practical examples of exception handling ....................................................................................... 445
Section 88.10: Exceptions are Objects too .............................................................................................................. 446
Section 88.11: Running clean-up code with finally .................................................................................................. 446
Section 88.12: Chain exceptions with raise from .................................................................................................... 447
Chapter 89: Raise Custom Errors / Exceptions ......................................................................................... 448
Section 89.1: Custom Exception ............................................................................................................................... 448
Section 89.2: Catch custom Exception .................................................................................................................... 448
Chapter 90: Commonwealth Exceptions ....................................................................................................... 450
Section 90.1: Other Errors ......................................................................................................................................... 450
Section 90.2: NameError: name '???' is not defined .............................................................................................. 451
Section 90.3: TypeErrors .......................................................................................................................................... 452
Section 90.4: Syntax Error on good code ............................................................................................................... 453
Section 90.5: IndentationErrors (or indentation SyntaxErrors) ............................................................................ 454
Chapter 91: urllib ....................................................................................................................................................... 456
Section 91.1: HTTP GET .............................................................................................................................................. 456
Section 91.2: HTTP POST .......................................................................................................................................... 456
Section 91.3: Decode received bytes according to content type encoding ........................................................ 457
Chapter 92: Web scraping with Python ......................................................................................................... 458
Section 92.1: Scraping using the Scrapy framework ............................................................................................. 458
Section 92.2: Scraping using Selenium WebDriver ................................................................................................ 458
Section 92.3: Basic example of using requests and lxml to scrape some data ................................................. 459
Section 92.4: Maintaining web-scraping session with requests ........................................................................... 459
Section 92.5: Scraping using BeautifulSoup4 ......................................................................................................... 460
Section 92.6: Simple web content download with urllib.request .......................................................................... 460
Section 92.7: Modify Scrapy user agent ................................................................................................................. 460
Section 92.8: Scraping with curl ............................................................................................................................... 460
Chapter 93: HTML Parsing .................................................................................................................................... 462
Section 93.1: Using CSS selectors in BeautifulSoup ................................................................................................ 462
Section 93.2: PyQuery ............................................................................................................................................... 462
Section 93.3: Locate a text after an element in BeautifulSoup ............................................................................ 463
Chapter 94: Manipulating XML .......................................................................................................................... 464
Section 94.1: Opening and reading using an ElementTree ................................................................................... 464
Section 94.2: Create and Build XML Documents .................................................................................................... 464
Section 94.3: Modifying an XML File ........................................................................................................................ 465
Section 94.4: Searching the XML with XPath .......................................................................................................... 465
Section 94.5: Opening and reading large XML files using iterparse (incremental parsing) ............................. 466
Chapter 95: Python Requests Post .................................................................................................................. 468
Section 95.1: Simple Post .......................................................................................................................................... 468
Section 95.2: Form Encoded Data ........................................................................................................................... 469
Section 95.3: File Upload .......................................................................................................................................... 469
Section 95.4: Responses ........................................................................................................................................... 470
Section 95.5: Authentication ..................................................................................................................................... 470
Section 95.6: Proxies ................................................................................................................................................. 471
Chapter 96: Distribution ........................................................................................................................................ 473
Section 96.1: py2app ................................................................................................................................................. 473
Section 96.2: cx_Freeze ............................................................................................................................................ 474
Chapter 97: Property Objects ............................................................................................................................ 475
Section 97.1: Using the @property decorator for read-write properties ............................................................. 475
Section 97.2: Using the @property decorator ....................................................................................................... 475
Section 97.3: Overriding just a getter, setter or a deleter of a property object ................................................. 476
Section 97.4: Using properties without decorators ................................................................................................ 476
Chapter 98: Overloading ...................................................................................................................................... 479
Section 98.1: Operator overloading ......................................................................................................................... 479
Section 98.2: Magic/Dunder Methods .................................................................................................................... 480
Section 98.3: Container and sequence types ......................................................................................................... 481
Section 98.4: Callable types ..................................................................................................................................... 482
Section 98.5: Handling unimplemented behaviour ................................................................................................ 482
Chapter 99: Polymorphism .................................................................................................................................. 484
Section 99.1: Duck Typing ......................................................................................................................................... 484
Section 99.2: Basic Polymorphism .......................................................................................................................... 484
Chapter 100: Method Overriding ...................................................................................................................... 488
Section 100.1: Basic method overriding ................................................................................................................... 488
Chapter 101: User-Defined Methods ................................................................................................................ 489
Section 101.1: Creating user-defined method objects ............................................................................................ 489
Section 101.2: Turtle example ................................................................................................................................... 490
Chapter 102: String representations of class instances: __str__ and __repr__
methods ........................................................................................................................................................................ 491
Section 102.1: Motivation ........................................................................................................................................... 491
Section 102.2: Both methods implemented, eval-round-trip style __repr__() .................................................. 495
Chapter 103: Debugging ........................................................................................................................................ 496
Section 103.1: Via IPython and ipdb ......................................................................................................................... 496
Section 103.2: The Python Debugger: Step-through Debugging with _pdb_ .................................................... 496
Section 103.3: Remote debugger ............................................................................................................................. 498
Chapter 104: Reading and Writing CSV ........................................................................................................ 499
Section 104.1: Using pandas ..................................................................................................................................... 499
Section 104.2: Writing a TSV file .............................................................................................................................. 499
Chapter 105: Writing to CSV from String or List ...................................................................................... 501
Section 105.1: Basic Write Example .......................................................................................................................... 501
Section 105.2: Appending a String as a newline in a CSV file ............................................................................... 501
Chapter 106: Dynamic code execution with `exec` and `eval` ............................................................. 502
Section 106.1: Executing code provided by untrusted user using exec, eval, or ast.literal_eval ....................... 502
Section 106.2: Evaluating a string containing a Python literal with ast.literal_eval ........................................... 502
Section 106.3: Evaluating statements with exec ..................................................................................................... 502
Section 106.4: Evaluating an expression with eval ................................................................................................. 503
Section 106.5: Precompiling an expression to evaluate it multiple times ............................................................ 503
Section 106.6: Evaluating an expression with eval using custom globals ........................................................... 503
Chapter 107: PyInstaller - Distributing Python Code .............................................................................. 504
Section 107.1: Installation and Setup ........................................................................................................................ 504
Section 107.2: Using Pyinstaller ................................................................................................................................ 504
Section 107.3: Bundling to One Folder ..................................................................................................................... 505
Section 107.4: Bundling to a Single File ................................................................................................................... 505
Chapter 108: Data Visualization with Python ............................................................................................. 506
Section 108.1: Seaborn .............................................................................................................................................. 506
Section 108.2: Matplotlib ........................................................................................................................................... 508
Section 108.3: Plotly ................................................................................................................................................... 509
Section 108.4: MayaVI ............................................................................................................................................... 511
Chapter 109: The Interpreter (Command Line Console) ....................................................................... 513
Section 109.1: Getting general help .......................................................................................................................... 513
Section 109.2: Referring to the last expression ...................................................................................................... 513
Section 109.3: Opening the Python console ............................................................................................................ 514
Section 109.4: The PYTHONSTARTUP variable ...................................................................................................... 514
Section 109.5: Command line arguments ............................................................................................................... 514
Section 109.6: Getting help about an object ........................................................................................................... 515
Chapter 110: *args and **kwargs ....................................................................................................................... 518
Section 110.1: Using **kwargs when writing functions ............................................................................................ 518
Section 110.2: Using *args when writing functions .................................................................................................. 518
Section 110.3: Populating kwarg values with a dictionary ..................................................................................... 519
Section 110.4: Keyword-only and Keyword-required arguments ........................................................................ 519
Section 110.5: Using **kwargs when calling functions ............................................................................................ 519
Section 110.6: **kwargs and default values ............................................................................................................. 519
Section 110.7: Using *args when calling functions .................................................................................................. 520
Chapter 111: Garbage Collection ........................................................................................................................ 521
Section 111.1: Reuse of primitive objects .................................................................................................................. 521
Section 111.2: Eects of the del command .............................................................................................................. 521
Section 111.3: Reference Counting ............................................................................................................................ 522
Section 111.4: Garbage Collector for Reference Cycles ......................................................................................... 522
Section 111.5: Forcefully deallocating objects ......................................................................................................... 523
Section 111.6: Viewing the refcount of an object ..................................................................................................... 524
Section 111.7: Do not wait for the garbage collection to clean up ........................................................................ 524
Section 111.8: Managing garbage collection ........................................................................................................... 524
Chapter 112: Pickle data serialisation ............................................................................................................. 526
Section 112.1: Using Pickle to serialize and deserialize an object .......................................................................... 526
Section 112.2: Customize Pickled Data .................................................................................................................... 526
Chapter 113: Binary Data ...................................................................................................................................... 528
Section 113.1: Format a list of values into a byte object ........................................................................................ 528
Section 113.2: Unpack a byte object according to a format string ...................................................................... 528
Section 113.3: Packing a structure ............................................................................................................................ 528
Chapter 114: Idioms .................................................................................................................................................. 530
Section 114.1: Dictionary key initializations .............................................................................................................. 530
Section 114.2: Switching variables ............................................................................................................................ 530
Section 114.3: Use truth value testing ...................................................................................................................... 530
Section 114.4: Test for "__main__" to avoid unexpected code execution .......................................................... 531
Chapter 115: Data Serialization .......................................................................................................................... 533
Section 115.1: Serialization using JSON .................................................................................................................... 533
Section 115.2: Serialization using Pickle ................................................................................................................... 533
Chapter 116: Multiprocessing ............................................................................................................................... 535
Section 116.1: Running Two Simple Processes ......................................................................................................... 535
Section 116.2: Using Pool and Map ........................................................................................................................... 535
Chapter 117: Multithreading ................................................................................................................................. 537
Section 117.1: Basics of multithreading .................................................................................................................... 537
Section 117.2: Communicating between threads .................................................................................................... 538
Section 117.3: Creating a worker pool ...................................................................................................................... 539
Section 117.4: Advanced use of multithreads .......................................................................................................... 539
Section 117.5: Stoppable Thread with a while Loop ............................................................................................... 541
Chapter 118: Processes and Threads .............................................................................................................. 542
Section 118.1: Global Interpreter Lock ...................................................................................................................... 542
Section 118.2: Running in Multiple Threads ............................................................................................................. 543
Section 118.3: Running in Multiple Processes .......................................................................................................... 544
Section 118.4: Sharing State Between Threads ....................................................................................................... 544
Section 118.5: Sharing State Between Processes .................................................................................................... 545
Chapter 119: Python concurrency ..................................................................................................................... 546
Section 119.1: The multiprocessing module ............................................................................................................. 546
Section 119.2: The threading module ....................................................................................................................... 547
Section 119.3: Passing data between multiprocessing processes ........................................................................ 547
Chapter 120: Parallel computation .................................................................................................................. 550
Section 120.1: Using the multiprocessing module to parallelise tasks ................................................................. 550
Section 120.2: Using a C-extension to parallelize tasks ........................................................................................ 550
Section 120.3: Using Parent and Children scripts to execute code in parallel .................................................... 550
Section 120.4: Using PyPar module to parallelize .................................................................................................. 551
Chapter 121: Sockets ................................................................................................................................................ 552
Section 121.1: Raw Sockets on Linux ......................................................................................................................... 552
Section 121.2: Sending data via UDP ....................................................................................................................... 552
Section 121.3: Receiving data via UDP ..................................................................................................................... 553
Section 121.4: Sending data via TCP ........................................................................................................................ 553
Section 121.5: Multi-threaded TCP Socket Server ................................................................................................... 553
Chapter 122: Websockets ...................................................................................................................................... 556
Section 122.1: Simple Echo with aiohttp ................................................................................................................... 556
Section 122.2: Wrapper Class with aiohttp ............................................................................................................. 556
Section 122.3: Using Autobahn as a Websocket Factory ...................................................................................... 557
Chapter 123: Sockets And Message Encryption/Decryption Between Client and Server
............................................................................................................................................................................................ 559
Section 123.1: Server side Implementation .............................................................................................................. 559
Section 123.2: Client side Implementation .............................................................................................................. 561
Chapter 124: Python Networking ..................................................................................................................... 563
Section 124.1: Creating a Simple Http Server .......................................................................................................... 563
Section 124.2: Creating a TCP server ...................................................................................................................... 563
Section 124.3: Creating a UDP Server ..................................................................................................................... 564
Section 124.4: Start Simple HttpServer in a thread and open the browser ......................................................... 564
Section 124.5: The simplest Python socket client-server example ....................................................................... 565
Chapter 125: Python HTTP Server .................................................................................................................... 567
Section 125.1: Running a simple HTTP server ......................................................................................................... 567
Section 125.2: Serving files ........................................................................................................................................ 567
Section 125.3: Basic handling of GET, POST, PUT using BaseHTTPRequestHandler ......................................... 568
Section 125.4: Programmatic API of SimpleHTTPServer ....................................................................................... 569
Chapter 126: Flask .................................................................................................................................................... 571
Section 126.1: Files and Templates ........................................................................................................................... 571
Section 126.2: The basics .......................................................................................................................................... 571
Section 126.3: Routing URLs ..................................................................................................................................... 572
Section 126.4: HTTP Methods ................................................................................................................................... 573
Section 126.5: Jinja Templating ............................................................................................................................... 573
Section 126.6: The Request Object .......................................................................................................................... 574
Chapter 127: Introduction to RabbitMQ using AMQPStorm ................................................................ 576
Section 127.1: How to consume messages from RabbitMQ .................................................................................. 576
Section 127.2: How to publish messages to RabbitMQ ......................................................................................... 577
Section 127.3: How to create a delayed queue in RabbitMQ ................................................................................ 577
Chapter 128: Descriptor ......................................................................................................................................... 580
Section 128.1: Simple descriptor ............................................................................................................................... 580
Section 128.2: Two-way conversions ....................................................................................................................... 581
Chapter 129: tempfile NamedTemporaryFile ............................................................................................. 582
Section 129.1: Create (and write to a) known, persistent temporary file ............................................................. 582
Chapter 130: Input, Subset and Output External Data Files using Pandas ................................. 584
Section 130.1: Basic Code to Import, Subset and Write External Data Files Using Pandas ............................... 584
Chapter 131: Unzipping Files ................................................................................................................................ 586
Section 131.1: Using Python ZipFile.extractall() to decompress a ZIP file ............................................................ 586
Section 131.2: Using Python TarFile.extractall() to decompress a tarball ........................................................... 586
Chapter 132: Working with ZIP archives ........................................................................................................ 587
Section 132.1: Examining Zipfile Contents ............................................................................................................... 587
Section 132.2: Opening Zip Files ............................................................................................................................... 587
Section 132.3: Extracting zip file contents to a directory ....................................................................................... 588
Section 132.4: Creating new archives ...................................................................................................................... 588
Chapter 133: Getting start with GZip .............................................................................................................. 589
Section 133.1: Read and write GNU zip files ............................................................................................................ 589
Chapter 134: Stack ................................................................................................................................................... 590
Section 134.1: Creating a Stack class with a List Object ........................................................................................ 590
Section 134.2: Parsing Parentheses ......................................................................................................................... 591
Chapter 135: Working around the Global Interpreter Lock (GIL) ..................................................... 593
Section 135.1: Multiprocessing.Pool .......................................................................................................................... 593
Section 135.2: Cython nogil: ...................................................................................................................................... 594
Chapter 136: Deployment ..................................................................................................................................... 595
Section 136.1: Uploading a Conda Package ............................................................................................................ 595
Chapter 137: Logging .............................................................................................................................................. 597
Section 137.1: Introduction to Python Logging ........................................................................................................ 597
Section 137.2: Logging exceptions ........................................................................................................................... 598
Chapter 138: Web Server Gateway Interface (WSGI) ............................................................................. 601
Section 138.1: Server Object (Method) ..................................................................................................................... 601
Chapter 139: Python Server Sent Events ...................................................................................................... 602
Section 139.1: Flask SSE ............................................................................................................................................. 602
Section 139.2: Asyncio SSE ........................................................................................................................................ 602
Chapter 140: Alternatives to switch statement from other languages ....................................... 604
Section 140.1: Use what the language oers: the if/else construct ..................................................................... 604
Section 140.2: Use a dict of functions ...................................................................................................................... 604
Section 140.3: Use class introspection ..................................................................................................................... 605
Section 140.4: Using a context manager ................................................................................................................ 606
Chapter 141: List destructuring (aka packing and unpacking) ......................................................... 607
Section 141.1: Destructuring assignment ................................................................................................................. 607
Section 141.2: Packing function arguments ............................................................................................................ 608
Section 141.3: Unpacking function arguments ........................................................................................................ 610
Chapter 142: Accessing Python source code and bytecode .............................................................. 611
Section 142.1: Display the bytecode of a function .................................................................................................. 611
Section 142.2: Display the source code of an object ............................................................................................. 611
Section 142.3: Exploring the code object of a function .......................................................................................... 612
Chapter 143: Mixins .................................................................................................................................................. 613
Section 143.1: Mixin ..................................................................................................................................................... 613
Section 143.2: Overriding Methods in Mixins ........................................................................................................... 614
Chapter 144: Attribute Access ........................................................................................................................... 615
Section 144.1: Basic Attribute Access using the Dot Notation ............................................................................... 615
Section 144.2: Setters, Getters & Properties ............................................................................................................ 615
Chapter 145: ArcPy .................................................................................................................................................. 618
Section 145.1: createDissolvedGDB to create a file gdb on the workspace ........................................................ 618
Section 145.2: Printing one field's value for all rows of feature class in file geodatabase using Search
Cursor ................................................................................................................................................................. 618
Chapter 146: Abstract Base Classes (abc) ................................................................................................... 619
Section 146.1: Setting the ABCMeta metaclass ....................................................................................................... 619
Section 146.2: Why/How to use ABCMeta and @abstractmethod ...................................................................... 619
Chapter 147: Plugin and Extension Classes ................................................................................................. 621
Section 147.1: Mixins ................................................................................................................................................... 621
Section 147.2: Plugins with Customized Classes ..................................................................................................... 622
Chapter 148: Immutable datatypes(int, float, str, tuple and frozensets) .................................. 624
Section 148.1: Individual characters of strings are not assignable ....................................................................... 624
Section 148.2: Tuple's individual members aren't assignable ............................................................................... 624
Section 148.3: Frozenset's are immutable and not assignable ............................................................................. 624
Chapter 149: Incompatibilities moving from Python 2 to Python 3 ................................................ 625
Section 149.1: Integer Division ................................................................................................................................... 625
Section 149.2: Unpacking Iterables .......................................................................................................................... 626
Section 149.3: Strings: Bytes versus Unicode .......................................................................................................... 628
Section 149.4: Print statement vs. Print function .................................................................................................... 630
Section 149.5: Dierences between range and xrange functions ........................................................................ 631
Section 149.6: Raising and handling Exceptions ..................................................................................................... 632
Section 149.7: Leaked variables in list comprehension .......................................................................................... 634
Section 149.8: True, False and None ........................................................................................................................ 635
Section 149.9: User Input ........................................................................................................................................... 635
Section 149.10: Comparison of dierent types ....................................................................................................... 636
Section 149.11: .next() method on iterators renamed ............................................................................................. 636
Section 149.12: filter(), map() and zip() return iterators instead of sequences ................................................... 637
Section 149.13: Renamed modules ........................................................................................................................... 637
Section 149.14: Removed operators <> and ``, synonymous with != and repr() ................................................... 638
Section 149.15: long vs. int ......................................................................................................................................... 638
Section 149.16: All classes are "new-style classes" in Python 3 ............................................................................ 639
Section 149.17: Reduce is no longer a built-in ......................................................................................................... 640
Section 149.18: Absolute/Relative Imports .............................................................................................................. 640
Section 149.19: map() ................................................................................................................................................ 642
Section 149.20: The round() function tie-breaking and return type .................................................................... 643
Section 149.21: File I/O .............................................................................................................................................. 644
Section 149.22: cmp function removed in Python 3 ............................................................................................... 644
Section 149.23: Octal Constants ............................................................................................................................... 645
Section 149.24: Return value when writing to a file object .................................................................................... 645
Section 149.25: exec statement is a function in Python 3 ...................................................................................... 645
Section 149.26: encode/decode to hex no longer available ................................................................................. 646
Section 149.27: Dictionary method changes .......................................................................................................... 647
Section 149.28: Class Boolean Value ....................................................................................................................... 647
Section 149.29: hasattr function bug in Python 2 ................................................................................................... 648
Chapter 150: 2to3 tool ............................................................................................................................................ 650
Section 150.1: Basic Usage ........................................................................................................................................ 650
Chapter 151: Non-ocial Python implementations ................................................................................ 652
Section 151.1: IronPython ........................................................................................................................................... 652
Section 151.2: Jython ................................................................................................................................................. 652
Section 151.3: Transcrypt .......................................................................................................................................... 653
Chapter 152: Abstract syntax tree ................................................................................................................... 656
Section 152.1: Analyze functions in a python script ................................................................................................ 656
Chapter 153: Unicode and bytes ....................................................................................................................... 658
Section 153.1: Encoding/decoding error handling .................................................................................................. 658
Section 153.2: File I/O ................................................................................................................................................ 658
Section 153.3: Basics .................................................................................................................................................. 659
Chapter 154: Python Serial Communication (pyserial) ......................................................................... 661
Section 154.1: Initialize serial device ......................................................................................................................... 661
Section 154.2: Read from serial port ....................................................................................................................... 661
Section 154.3: Check what serial ports are available on your machine .............................................................. 661
Chapter 155: Neo4j and Cypher using Py2Neo ......................................................................................... 664
Section 155.1: Adding Nodes to Neo4j Graph .......................................................................................................... 664
Section 155.2: Importing and Authenticating .......................................................................................................... 664
Section 155.3: Adding Relationships to Neo4j Graph ............................................................................................. 664
Section 155.4: Query 1 : Autocomplete on News Titles .......................................................................................... 664
Section 155.5: Query 2 : Get News Articles by Location on a particular date ..................................................... 665
Section 155.6: Cypher Query Samples .................................................................................................................... 665
Chapter 156: Basic Curses with Python .......................................................................................................... 666
Section 156.1: The wrapper() helper function ......................................................................................................... 666
Section 156.2: Basic Invocation Example ................................................................................................................ 666
Chapter 157: Templates in python ................................................................................................................... 667
Section 157.1: Simple data output program using template ................................................................................. 667
Section 157.2: Changing delimiter ............................................................................................................................ 667
Chapter 158: Pillow ................................................................................................................................................... 668
Section 158.1: Read Image File ................................................................................................................................. 668
Section 158.2: Convert files to JPEG ........................................................................................................................ 668
Chapter 159: The pass statement .................................................................................................................... 669
Section 159.1: Ignore an exception ........................................................................................................................... 669
Section 159.2: Create a new Exception that can be caught .................................................................................. 669
Chapter 160: CLI subcommands with precise help output .................................................................. 671
Section 160.1: Native way (no libraries) ................................................................................................................... 671
Section 160.2: argparse (default help formatter) .................................................................................................. 671
Section 160.3: argparse (custom help formatter) .................................................................................................. 672
Chapter 161: Database Access ............................................................................................................................ 674
Section 161.1: SQLite ................................................................................................................................................... 674
Section 161.2: Accessing MySQL database using MySQLdb ................................................................................. 679
Section 161.3: Connection .......................................................................................................................................... 680
Section 161.4: PostgreSQL Database access using psycopg2 .............................................................................. 681
Section 161.5: Oracle database ................................................................................................................................ 682
Section 161.6: Using sqlalchemy ............................................................................................................................... 684
Chapter 162: Connecting Python to SQL Server ....................................................................................... 685
Section 162.1: Connect to Server, Create Table, Query Data ................................................................................ 685
Chapter 163: PostgreSQL ...................................................................................................................................... 686
Section 163.1: Getting Started ................................................................................................................................... 686
Chapter 164: Python and Excel .......................................................................................................................... 687
Section 164.1: Read the excel data using xlrd module ........................................................................................... 687
Section 164.2: Format Excel files with xlsxwriter ..................................................................................................... 687
Section 164.3: Put list data into a Excel's file ........................................................................................................... 688
Section 164.4: OpenPyXL .......................................................................................................................................... 689
Section 164.5: Create excel charts with xlsxwriter .................................................................................................. 689
Chapter 165: Turtle Graphics .............................................................................................................................. 693
Section 165.1: Ninja Twist (Turtle Graphics) ............................................................................................................ 693
Chapter 166: Python Persistence ...................................................................................................................... 694
Section 166.1: Python Persistence ............................................................................................................................ 694
Section 166.2: Function utility for save and load .................................................................................................... 695
Chapter 167: Design Patterns ............................................................................................................................. 696
Section 167.1: Introduction to design patterns and Singleton Pattern ................................................................. 696
Section 167.2: Strategy Pattern ................................................................................................................................ 698
Section 167.3: Proxy ................................................................................................................................................... 699
Chapter 168: hashlib ................................................................................................................................................ 701
Section 168.1: MD5 hash of a string ......................................................................................................................... 701
Section 168.2: algorithm provided by OpenSSL ..................................................................................................... 702
Chapter 169: Creating a Windows service using Python ....................................................................... 703
Section 169.1: A Python script that can be run as a service .................................................................................. 703
Section 169.2: Running a Flask web application as a service ............................................................................... 704
Chapter 170: Mutable vs Immutable (and Hashable) in Python ....................................................... 706
Section 170.1: Mutable vs Immutable ....................................................................................................................... 706
Section 170.2: Mutable and Immutable as Arguments .......................................................................................... 708
Chapter 171: configparser .................................................................................................................................... 710
Section 171.1: Creating configuration file programmatically ................................................................................. 710
Section 171.2: Basic usage ......................................................................................................................................... 710
Chapter 172: Optical Character Recognition .............................................................................................. 711
Section 172.1: PyTesseract ........................................................................................................................................ 711
Section 172.2: PyOCR ................................................................................................................................................ 711
Chapter 173: Virtual environments .................................................................................................................. 713
Section 173.1: Creating and using a virtual environment ....................................................................................... 713
Section 173.2: Specifying specific python version to use in script on Unix/Linux ............................................... 715
Section 173.3: Creating a virtual environment for a dierent version of python ............................................... 715
Section 173.4: Making virtual environments using Anaconda .............................................................................. 715
Section 173.5: Managing multiple virtual environments with virtualenvwrapper ............................................... 716
Section 173.6: Installing packages in a virtual environment ................................................................................. 717
Section 173.7: Discovering which virtual environment you are using .................................................................. 718
Section 173.8: Checking if running inside a virtual environment .......................................................................... 719
Section 173.9: Using virtualenv with fish shell ......................................................................................................... 719
Chapter 174: Python Virtual Environment - virtualenv ......................................................................... 721
Section 174.1: Installation .......................................................................................................................................... 721
Section 174.2: Usage ................................................................................................................................................. 721
Section 174.3: Install a package in your Virtualenv ............................................................................................... 721
Section 174.4: Other useful virtualenv commands ................................................................................................. 722
Chapter 175: Virtual environment with virtualenvwrapper ................................................................ 724
Section 175.1: Create virtual environment with virtualenvwrapper ...................................................................... 724
Chapter 176: Create virtual environment with virtualenvwrapper in windows ........................ 726
Section 176.1: Virtual environment with virtualenvwrapper for windows ............................................................. 726
Chapter 177: sys ........................................................................................................................................................ 727
Section 177.1: Command line arguments ................................................................................................................ 727
Section 177.2: Script name ........................................................................................................................................ 727
Section 177.3: Standard error stream ...................................................................................................................... 727
Section 177.4: Ending the process prematurely and returning an exit code ....................................................... 727
Chapter 178: ChemPy - python package ...................................................................................................... 728
Section 178.1: Parsing formulae ............................................................................................................................... 728
Section 178.2: Balancing stoichiometry of a chemical reaction ........................................................................... 728
Section 178.3: Balancing reactions .......................................................................................................................... 728
Section 178.4: Chemical equilibria ............................................................................................................................ 729
Section 178.5: Ionic strength ..................................................................................................................................... 729
Section 178.6: Chemical kinetics (system of ordinary dierential equations) .................................................... 729
Chapter 179: pygame .............................................................................................................................................. 731
Section 179.1: Pygame's mixer module .................................................................................................................... 731
Section 179.2: Installing pygame .............................................................................................................................. 732
Chapter 180: Pyglet ................................................................................................................................................. 734
Section 180.1: Installation of Pyglet .......................................................................................................................... 734
Section 180.2: Hello World in Pyglet ........................................................................................................................ 734
Section 180.3: Playing Sound in Pyglet .................................................................................................................... 734
Section 180.4: Using Pyglet for OpenGL ................................................................................................................. 734
Section 180.5: Drawing Points Using Pyglet and OpenGL ..................................................................................... 734
Chapter 181: Audio .................................................................................................................................................... 736
Section 181.1: Working with WAV files ...................................................................................................................... 736
Section 181.2: Convert any soundfile with python and mpeg ............................................................................ 736
Section 181.3: Playing Windows' beeps .................................................................................................................... 736
Section 181.4: Audio With Pyglet .............................................................................................................................. 737
Chapter 182: pyaudio .............................................................................................................................................. 738
Section 182.1: Callback Mode Audio I/O .................................................................................................................. 738
Section 182.2: Blocking Mode Audio I/O ................................................................................................................. 739
Chapter 183: shelve .................................................................................................................................................. 741
Section 183.1: Creating a new Shelf .......................................................................................................................... 741
Section 183.2: Sample code for shelve .................................................................................................................... 742
Section 183.3: To summarize the interface (key is a string, data is an arbitrary object): .................................. 742
Section 183.4: Write-back ......................................................................................................................................... 742
Chapter 184: IoT Programming with Python and Raspberry PI ....................................................... 744
Section 184.1: Example - Temperature sensor ........................................................................................................ 744
Chapter 185: kivy - Cross-platform Python Framework for NUI Development ....................... 748
Section 185.1: First App .............................................................................................................................................. 748
Chapter 186: Pandas Transform: Preform operations on groups and concatenate the
results ............................................................................................................................................................................. 750
Section 186.1: Simple transform ............................................................................................................................... 750
Section 186.2: Multiple results per group ................................................................................................................ 751
Chapter 187: Similarities in syntax, Dierences in meaning: Python vs. JavaScript ............. 752
Section 187.1: `in` with lists ......................................................................................................................................... 752
Chapter 188: Call Python from C# ................................................................................................................... 753
Section 188.1: Python script to be called by C# application .................................................................................. 753
Section 188.2: C# code calling Python script .......................................................................................................... 753
Chapter 189: ctypes ................................................................................................................................................. 755
Section 189.1: ctypes arrays ..................................................................................................................................... 755
Section 189.2: Wrapping functions for ctypes ........................................................................................................ 755
Section 189.3: Basic usage ........................................................................................................................................ 756
Section 189.4: Common pitfalls ................................................................................................................................ 756
Section 189.5: Basic ctypes object ........................................................................................................................... 757
Section 189.6: Complex usage .................................................................................................................................. 758
Chapter 190: Writing extensions ........................................................................................................................ 760
Section 190.1: Hello World with C Extension ............................................................................................................ 760
Section 190.2: C Extension Using c++ and Boost .................................................................................................... 760
Section 190.3: Passing an open file to C Extensions .............................................................................................. 762
Chapter 191: Python Lex-Yacc ............................................................................................................................. 763
Section 191.1: Getting Started with PLY .................................................................................................................... 763
Section 191.2: The "Hello, World!" of PLY - A Simple Calculator ............................................................................ 763
Section 191.3: Part 1: Tokenizing Input with Lex ....................................................................................................... 765
Section 191.4: Part 2: Parsing Tokenized Input with Yacc ...................................................................................... 768
Chapter 192: Unit Testing ...................................................................................................................................... 772
Section 192.1: Test Setup and Teardown within a unittest.TestCase .................................................................... 772
Section 192.2: Asserting on Exceptions ................................................................................................................... 772
Section 192.3: Testing Exceptions ............................................................................................................................ 773
Section 192.4: Choosing Assertions Within Unittests ............................................................................................. 774
Section 192.5: Unit tests with pytest ........................................................................................................................ 775
Section 192.6: Mocking functions with unittest.mock.create_autospec ............................................................... 778
Chapter 193: py.test ................................................................................................................................................. 780
Section 193.1: Setting up py.test ............................................................................................................................... 780
Section 193.2: Intro to Test Fixtures ......................................................................................................................... 780
Section 193.3: Failing Tests ....................................................................................................................................... 783
Chapter 194: Profiling ............................................................................................................................................. 785
Section 194.1: %%timeit and %timeit in IPython ...................................................................................................... 785
Section 194.2: Using cProfile (Preferred Profiler) ................................................................................................... 785
Section 194.3: timeit() function ................................................................................................................................. 785
Section 194.4: timeit command line ......................................................................................................................... 786
Section 194.5: line_profiler in command line .......................................................................................................... 786
Chapter 195: Python speed of program ....................................................................................................... 788
Section 195.1: Deque operations .............................................................................................................................. 788
Section 195.2: Algorithmic Notations ....................................................................................................................... 788
Section 195.3: Notation .............................................................................................................................................. 789
Section 195.4: List operations ................................................................................................................................... 790
Section 195.5: Set operations ................................................................................................................................... 790
Chapter 196: Performance optimization ....................................................................................................... 792
Section 196.1: Code profiling ..................................................................................................................................... 792
Chapter 197: Security and Cryptography .................................................................................................... 794
Section 197.1: Secure Password Hashing ................................................................................................................. 794
Section 197.2: Calculating a Message Digest ......................................................................................................... 794
Section 197.3: Available Hashing Algorithms .......................................................................................................... 794
Section 197.4: File Hashing ....................................................................................................................................... 795
Section 197.5: Generating RSA signatures using pycrypto ................................................................................... 795
Section 197.6: Asymmetric RSA encryption using pycrypto ................................................................................. 796
Section 197.7: Symmetric encryption using pycrypto ............................................................................................ 797
Chapter 198: Secure Shell Connection in Python ...................................................................................... 798
Section 198.1: ssh connection ................................................................................................................................... 798
Chapter 199: Python Anti-Patterns .................................................................................................................. 799
Section 199.1: Overzealous except clause ............................................................................................................... 799
Section 199.2: Looking before you leap with processor-intensive function ........................................................ 799
Chapter 200: Common Pitfalls ........................................................................................................................... 802
Section 200.1: List multiplication and common references .................................................................................. 802
Section 200.2: Mutable default argument .............................................................................................................. 805
Section 200.3: Changing the sequence you are iterating over ............................................................................ 806
Section 200.4: Integer and String identity .............................................................................................................. 809
Section 200.5: Dictionaries are unordered ............................................................................................................. 810
Section 200.6: Variable leaking in list comprehensions and for loops ................................................................ 811
Section 200.7: Chaining of or operator ................................................................................................................... 811
Section 200.8: sys.argv[0] is the name of the file being executed ...................................................................... 812
Section 200.9: Accessing int literals' attributes ...................................................................................................... 812
Section 200.10: Global Interpreter Lock (GIL) and blocking threads ................................................................... 813
Section 200.11: Multiple return .................................................................................................................................. 814
Section 200.12: Pythonic JSON keys ....................................................................................................................... 814
Chapter 201: Hidden Features ............................................................................................................................ 816
Section 201.1: Operator Overloading ....................................................................................................................... 816
Credits ............................................................................................................................................................................ 817
You may also like ...................................................................................................................................................... 831
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
https://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):
If you have Python 3 installed, and it is your default version (see Troubleshooting for more details) you should see
something like this:
$ 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')
Python 2 has a number of functionalities that can be optionally imported from Python 3 using the __future__
module, as discussed here.
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()
or
>>> 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
Programs - For long-term storage you can save content to .py files and edit/execute them as scripts or programs
with external tools e.g. shell, IDEs (such as PyCharm), Jupyter notebooks, etc. Intermediate users may use these
tools; however, the methods discussed here are sufficient for getting started.
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
0 = x
=> Output: SyntaxError: can't assign to literal
You can not use python's keywords as a valid variable name. You can see the list of keyword by:
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))
x = None
print(type(x))
# Output: <type 'NoneType'>
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)
When using such cascading assignment, it is important to note that all three variables a, b and c refer to the same
object in memory, an int object with the value of 1. In other words, a, b and c are three different names given to the
same int object. Assigning a different object to one of them afterwards doesn't change the others, just as expected:
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.
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
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]
b = ['a', 1, 'python', (1, 2), [1, 2]]
b[2] = 'something else' # allowed
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))
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:
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']
name.index("Alice")
0
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
A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is
separated by a comma and the key and value are separated by a colon. Here is an example:
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 an 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.
>>> state_capitals = {
'Arkansas': 'Little Rock',
'Colorado': 'Denver',
'California': 'Sacramento',
'Georgia': 'Atlanta'
}
>>> 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)
In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE can be a better learning experience for
new users because code is interpreted as the user writes.
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.
To get input from the user, use the input function (note: in Python 2.x, the function is called raw_input instead,
although Python 2.x has its own version of input that is completely different):
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
>>> dir(__builtins__)
[
'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BufferError',
'BytesWarning',
'DeprecationWarning',
'EOFError',
'Ellipsis',
'EnvironmentError',
'Exception',
'False',
'FloatingPointError',
'FutureWarning',
'GeneratorExit',
'IOError',
'ImportError',
'ImportWarning',
'IndentationError',
'IndexError',
'KeyError',
'KeyboardInterrupt',
'LookupError',
'MemoryError',
'NameError',
'None',
'NotImplemented',
'NotImplementedError',
'OSError',
'OverflowError',
'PendingDeprecationWarning',
'ReferenceError',
'RuntimeError',
'RuntimeWarning',
'StandardError',
'StopIteration',
'SyntaxError',
'SyntaxWarning',
'SystemError',
'SystemExit',
'TabError',
'True',
'TypeError',
'UnboundLocalError',
'UnicodeDecodeError',
'UnicodeEncodeError',
'UnicodeError',
'UnicodeTranslateError',
'UnicodeWarning',
'UserWarning',
'ValueError',
'Warning',
'ZeroDivisionError',
'__debug__',
'__doc__',
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.
In addition to functions, documentation can also be provided in modules. So, if you have a file named
helloWorld.py like this:
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()
# greet.py
import hello
hello.say_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:
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, Red Hat 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
python --version
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()
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
readable' string. If no argument is given, this returns the empty string, ''.
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
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> 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 an array of any data type or single data type.
list1 = ['hello','world']
print(list) #will output 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
Watch Today →
Chapter 5: Date and Time
Section 5.1: Parsing a string into a timezone aware datetime
object
Python 3.2+ has support for %z format when parsing a string into a datetime object.
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
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:
For example:
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
>>> d = {5, 6}
>>> a.isdisjoint(b) # {2, 3, 4} are in both sets
False
>>> a.isdisjoint(d)
True
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.
The numbers module contains the abstract metaclasses for the numerical types:
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:
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.
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.expm1(0) # 0.0
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
Any mathematic operator can be used before the '=' character to make an inplace operation:
Other in place operators exist for the bitwise operators (^, | etc)
a * b # = 6
import operator
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
-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:
Watch Today →
✔ Support Vector Machines
Chapter 10: Bitwise Operators
Bitwise operations alter binary strings at the bit level. These operations are incredibly basic and are directly
supported by the processor. These few operations are necessary in working with device drivers, low-level graphics,
cryptography, and network communications. This section provides useful knowledge and examples of Python's
bitwise operators.
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
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)
# 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
# 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
Python 3 added a new keyword called nonlocal. The nonlocal keyword adds a scope override to the inner scope.
You can read all about it in PEP 3104. This is best illustrated with a couple of code examples. One of the most
common examples is to create function that can increment:
def counter():
num = 0
def incrementer():
num += 1
return num
return incrementer
If you try running this code, you will receive an UnboundLocalError because the num variable is referenced before
it is assigned in the innermost function. Let's add nonlocal to the mix:
def counter():
num = 0
def incrementer():
nonlocal num
num += 1
return num
return incrementer
c = counter()
c() # = 1
c() # = 2
c() # = 3
Basically nonlocal will allow you to assign to variables in an outer scope, but not a global scope. So you can't use
nonlocal in our counter function because then it would try to assign to a global scope. Give it a try and you will
quickly get a SyntaxError. Instead you must use nonlocal in a nested function.
(Note that the functionality presented here is better implemented using generators.)
x = 'Hi'
def read_x():
print(x) # x is just referenced, therefore assumed global
read_x() # prints Hi
def read_y():
print(y) # here y is just referenced, therefore assumed global
def read_y():
y = 'Hey' # y appears in an assignment, therefore it's local
print(y) # will find the local y
def read_x_local_fail():
if False:
x = 'Hey' # x appears in an assignment, therefore it's local
print(x) # will look for the _local_ z, which is not assigned, and will not be found
Normally, an assignment inside a scope will shadow any outer variables of the same name:
x = 'Hi'
def change_local_x():
x = 'Bye'
print(x)
change_local_x() # prints Bye
print(x) # prints Hi
Declaring a name global means that, for the rest of the scope, any assignments to the name will happen at the
module's top level:
x = 'Hi'
def change_global_x():
global x
x = 'Bye'
print(x)
The global keyword means that assignments will happen at the module's top level, not at the program's top level.
Other modules will still need the usual dotted access to variables within the module.
To summarize: in order to know whether a variable x is local to a function, you should read the entire function:
def foo():
a = 5
print(a) # ok
def foo():
if True:
a = 5
print(a) # ok
b = 3
def bar():
if False:
b = 5
print(b) # UnboundLocalError: local variable 'b' referenced before assignment
Common binding operations are assignments, for loops, and augmented assignments such as a += 5
del v
If v is a variable, the command del v removes the variable from its scope. For example:
x = 5
print(x) # out: 5
del x
print(x) # NameError: name 'f' is not defined
Note that del is a binding occurrence, which means that unless explicitly stated otherwise (using nonlocal
or global), del v will make v local to the current scope. If you intend to delete v in an outer scope, use
nonlocal v or global v in the same scope of the del v statement.
In all the following, the intention of a command is a default behavior but is not enforced by the language. A class
might be written in a way that invalidates this intention.
del v.name
class A:
pass
a = A()
a.x = 7
print(a.x) # out: 7
del a.x
print(a.x) # error: AttributeError: 'A' object has no attribute 'x'
del v[item]
The intention is that item will not belong in the mapping implemented by the object v. For example:
The intention is similar to the one described above, but with slices - ranges of items instead of a single item. For
example:
x = [0, 1, 2, 3, 4]
del x[1:3]
print(x) # out: [0, 3, 4]
a = 'global'
class Fred:
a = 'class' # class scope
b = (a for i in range(10)) # function scope
c = [a for i in range(10)] # function scope
d = a # class scope
e = lambda: a # function scope
f = lambda a=a: a # default argument uses class scope
print(Fred.a) # class
print(next(Fred.b)) # global
print(Fred.c[0]) # class in Python 2, global in Python 3
print(Fred.d) # class
print(Fred.e()) # global
print(Fred.f()) # class
print(Fred.g()) # global
Users unfamiliar with how this scope works might expect b, c, and e to print class.
Names in class scope are not accessible. Names are resolved in the innermost enclosing function scope.
If a class definition occurs in a chain of nested scopes, the resolution process skips class definitions.
class A:
a = 42
b = list(a + i for i in range(10))
This example uses references from this answer by Martijn Pieters, which contains more in depth analysis of this
behavior.
All Python variables which are accessible at some point in code are either in local scope or in global scope.
The explanation is that local scope includes all variables defined in the current function and global scope includes
variables defined outside of the current function.
foo = 1 # global
def func():
bar = 2 # local
print(foo) # prints variable foo from global scope
print(bar) # prints variable bar from local scope
One can inspect which variables are in which scope. Built-in functions locals() and globals() return the whole
scopes as dictionaries.
foo = 1
def func():
bar = 2
print(globals().keys()) # prints all variable names in global scope
print(locals().keys()) # prints all variable names in local scope
def func():
foo = 2 # creates a new variable foo in local scope, global foo is not affected
print(foo) # prints 2
foo = 1
def func():
global foo
foo = 2 # this modifies the global foo, rather than creating a local variable
What it means is that a variable will never be global for a half of the function and local afterwards, or vice-versa.
foo = 1
def func():
# This function has a local variable foo, because it is defined down below.
# So, foo is local from this point. Global foo is hidden.
foo = 1
def func():
# In this function, foo is a global variable from the beginning
print(foo) # 7
print(globals()['foo']) # 7
There may be many levels of functions nested within functions, but within any one function there is only one local
scope for that function and the global scope. There are no intermediate scopes.
foo = 1
def f1():
bar = 1
def f2():
baz = 2
# here, foo is a global variable, baz is a local variable
# bar is not in either scope
print(locals().keys()) # ['baz']
print('bar' in locals()) # False
print('bar' in globals()) # False
def f3():
baz = 3
print(bar) # bar from f1 is referenced so it enters local scope of f3 (closure)
print(locals().keys()) # ['bar', 'baz']
print('bar' in locals()) # True
print('bar' in globals()) # False
def f4():
bar = 4 # a new local bar which hides bar from local scope of f1
baz = 4
print(bar)
print(locals().keys()) # ['bar', 'baz']
print('bar' in locals()) # True
Both these keywords are used to gain write access to variables which are not local to the current functions.
The global keyword declares that a name should be treated as a global variable.
def f1():
foo = 1 # a new foo local in f1
def f2():
foo = 2 # a new foo local in f2
def f3():
foo = 3 # a new foo local in f3
print(foo) # 3
foo = 30 # modifies local foo in f3 only
def f4():
global foo
print(foo) # 0
foo = 100 # modifies global foo
On the other hand, nonlocal (see Nonlocal Variables ), available in Python 3, takes a local variable from an
enclosing scope into the local scope of current function.
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest
enclosing scope excluding globals.
def f1():
def f2():
foo = 2 # a new foo local in f2
def f3():
nonlocal foo # foo from f2, which is the nearest enclosing scope
print(foo) # 2
foo = 20 # modifies foo from f2!
Each of the above statements is a binding occurrence - x become bound to the object denoted by 5. If this statement
appears inside a function, then x will be function-local by default. See the "Syntax" section for a list of binding
statements.
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
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:
aDate=datetime.date.today()
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!
Watch Today →
Chapter 15: Comparisons
Parameter Details
x First item to be compared
y Second item to be compared
x > y > z
a OP b OP c OP d ...
Where OP represents one of the multiple comparison operations you can use, and the letters represent arbitrary
valid expressions.
Note that 0 != 1 != 0 evaluates to True, even though 0 != 0 is False. Unlike the common mathematical
notation in which x != y != z means that x, y and z have different values. Chaining == operations has
the natural meaning in most cases, since equality is generally transitive.
Style
There is no theoretical limit on how many items and comparison operations you use as long you have proper
syntax:
The above returns True if each comparison returns True. However, using convoluted chaining is not a good style. A
good chaining will be "directional", not more complicated than
Side effects
As soon as one comparison returns False, the expression evaluates immediately to False, skipping all remaining
comparisons.
Note that the expression exp in a > exp > b will be evaluated only once, whereas in the case of
To illustrate:
a = 'Python is fun!'
b = 'Python is fun!'
a == b # returns True
a is b # returns False
a = [1, 2, 3, 4, 5]
b = a # b references a
a == b # True
a is b # True
b = a[:] # b now references a copy of a
a == b # True
a is b # False [!!]
Beyond this, there are quirks of the run-time environment that further complicate things. Short strings and small
integers will return True when compared with is, due to the Python machine attempting to use less memory for
identical objects.
a = 'short'
b = 'short'
c = 5
d = 5
a is b # True
c is d # True
a = 'not so short'
b = 'not so short'
c = 1000
d = 1000
a is b # False
c is d # False
sentinel = object()
def myfunc(var=sentinel):
These operators compare two types of values, they're the less than and greater than operators. For numbers this
simply compares the numerical values to see which is larger:
12 > 4
# True
12 < 4
# False
1 < 4
# True
For strings they will compare lexicographically, which is similar to alphabetical order but not quite the same.
In these comparisons, lowercase letters are considered 'greater than' uppercase, which is why "gamma" < "OMEGA"
is false. If they were all uppercase it would return the expected alphabetical ordering result:
Each type defines it's calculation with the < and > operators differently, so you should investigate what the
operators mean with a given type before using it.
This returns True if x and y are not equal and otherwise returns False.
12 != 1
# True
12 != '12'
# True
'12' != '12'
# False
This expression evaluates if x and y are the same value and returns the result as a boolean value. Generally both
type and value need to match, so the int 12 is not the same as the string '12'.
12 == 12
# True
12 == 1
# False
'12' == '12'
# True
'spam' == 'spam'
# True
'spam' == 'spam '
# False
'12' == 12
# False
Note that each type has to define a function that will be used to evaluate if two values are the same. For builtin
types these functions behave as you'd expect, and just evaluate things based on being the same value. However
custom types could define equality testing as whatever they'd like, including always returning True or always
returning False.
class Foo(object):
def __init__(self, item):
self.my_item = item
def __eq__(self, other):
return self.my_item == other.my_item
a = Foo(5)
b = Foo(5)
a == b # True
a != b # False
a is b # False
Note that this simple comparison assumes that other (the object being compared to) is the same object type.
Comparing to another type will throw an error:
class Bar(object):
def __init__(self, item):
self.other_item = item
def __eq__(self, other):
return self.other_item == other.other_item
def __ne__(self, other):
return self.other_item != other.other_item
c = Bar(5)
a == c # throws AttributeError: 'Foo' object has no attribute 'other_item'
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.
continue 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:
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 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))
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>>
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):
In this example, nothing will happen. The for loop will complete without error, but no commands or code will be
actioned. pass allows us to run our code successfully without having all commands and action fully implemented.
Similarly, pass can be used in while loops, as well as in selections and function definitions etc.
while x == y:
pass
for key in d:
print(key)
Output:
"a"
"b"
"c"
or in Python 2:
Output:
1
2
3
Output:
Note that in Python 2, .keys(), .values() and .items() return a list object. If you simply need to iterate through
the result, you can use the equivalent .iterkeys(), .itervalues() and .iteritems().
The difference between .keys() and .iterkeys(), .values() and .itervalues(), .items() and .iteritems() is
that the iter* methods are generators. Thus, the elements within the dictionary are yielded one by one as they are
evaluated. When a list object is returned, all of the elements are packed into a list and then returned for further
evaluation.
Note also that in Python 3, Order of items printed in the above manner does not follow any order.
a = 10
while True:
a = a-1
print(a)
if a<7:
break
print('Done.')
9
8
7
6
Done.
collection = [('a', 'b', 'c'), ('x', 'y', 'z'), ('1', '2', '3')]
This will also work for most types of iterables, not just tuples.
To iterate over each element in the list, a for loop like below can be used:
for s in lst:
print s[:1] # print the first letter
The for loop assigns s for each element of lst. This will print:
a
b
c
d
e
Often you need both the element and the index of that element. The enumerate keyword performs that task.
The index idx will start with zero and increment for each iteration, while the s will contain the element being
processed. The previous snippet will output:
If we want to iterate over a range (remembering that Python uses zero-based indexing), use the range keyword.
The list may also be sliced. The following slice notation goes from element at index 1 to the end with a step of 2.
The two for loops give the same result.
for s in lst[1::2]:
print(s)
bravo
delta
i = 0
while i < 4:
#loop statements
i = i + 1
While the above loop can easily be translated into a more elegant for loop, while loops are useful for checking if
some condition has been met. The following loop will continue to execute until myObject is ready.
myObject = anObject()
while myObject.isNotReady():
myObject.tryToGetReady()
while loops can also run without a condition by using numbers (complex or real) or True:
import cmath
complex_num = cmath.sqrt(-1)
while complex_num: # You can also replace complex_num with any number, True or a value of any
type
print(complex_num) # Prints 1j forever
If the condition is always true the while loop will run forever (infinite loop) if it is not terminated by a break or return
statement or an exception.
while True:
print "Infinite loop"
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:
Typecodes are the codes that are used to define the type of array values or the type of array. The table in the
parameters section shows the possible values you can use when declaring an array and it's type.
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.
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 17.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
lst=[[1,2,3],[4,5,6],[7,8,9]]
here the outer list lst has three things in it. each of those things is another list: The first one is: [1,2,3], the second
one is: [4,5,6] and the third one is: [7,8,9]. You can access these lists the same way you would access another
other element of a list, like this:
print (lst[0])
#output: [1, 2, 3]
print (lst[1])
#output: [4, 5, 6]
print (lst[2])
#output: [7, 8, 9]
You can then access the different elements in each of those lists the same way:
print (lst[0][0])
#output: 1
print (lst[0][1])
#output: 2
Here the first number inside the [] brackets means get the list in that position. In the above example we used the
number 0 to mean get the list in the 0th position which is [1,2,3]. The second set of [] brackets means get the
item in that position from the inner list. In this case we used both 0 and 1 the 0th position in the list we got is the
number 1 and in the 1st position it is 2
You can also set values inside these lists the same way:
lst[0]=[10,11,12]
Now the list is [[10,11,12],[4,5,6],[7,8,9]]. In this example we changed the whole first list to be a completely
new list.
lst[1][2]=15
Now the list is [[10,11,12],[4,5,15],[7,8,9]]. In this example we changed a single element inside of one of the
inner lists. First we went into the list at position 1 and changed the element within it at position 2, which was 6 now
it's 15.
[[[111,112,113],[121,122,123],[131,132,133]],[[211,212,213],[221,222,223],[231,232,233]],[[311,312,
313],[321,322,323],[331,332,333]]]
[[[111,112,113],[121,122,123],[131,132,133]],\
[[211,212,213],[221,222,223],[231,232,233]],\
[[311,312,313],[321,322,323],[331,332,333]]]
By nesting the lists like this, you can extend to arbitrarily high dimensions.
print(myarray)
print(myarray[1])
print(myarray[2][1])
print(myarray[1][0][2])
etc.
myarray[1]=new_n-1_d_list
myarray[2][1]=new_n-2_d_list
myarray[1][0][2]=new_n-3_d_list #or a single number if you're dealing with 3D arrays
etc.
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 iterators.
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',
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
>>>
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
Watch Today →
Chapter 20: List
The Python List is a general data structure widely used in Python programs. They are found in other languages,
often referred to as dynamic arrays. They are both mutable and a sequence data type that allows them to be indexed
and sliced. The list can contain different types of objects, including other list objects.
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
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
readable. While this works in Python 3:
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'
]
For each <element> in <iterable>; if <condition> evaluates to True, add <expression> (usually a function of
<element>) to the returned list.
For example, this can be used to extract only even numbers from a sequence of integers:
[x for x in range(10) if x % 2 == 0]
# Out: [0, 2, 4, 6, 8]
Live demo
even_numbers = []
print(even_numbers)
# Out: [0, 2, 4, 6, 8]
Also, a conditional list comprehension of the form [e for x in y if c] (where e and c are expressions in terms of
x) is equivalent to list(filter(lambda x: c, map(lambda x: e, y))).
Despite providing the same result, pay attention to the fact that the former example is almost 2x faster than the
latter one. For those who are curious, this is a nice explanation of the reason why.
Note that this is quite different from the ... if ... else ... conditional expression (sometimes known as a
ternary expression) that you can use for the <expression> part of the list comprehension. Consider the following
example:
Live demo
Here the conditional expression isn't a filter, but rather an operator determining the value to be used for the list
items:
Live demo
If you are using Python 2.7, xrange may be better than range for several reasons as described in the xrange
documentation.
numbers = []
for x in range(10):
if x % 2 == 0:
temp = x
else:
temp = -1
numbers.append(2 * temp + 1)
print(numbers)
# Out: [1, -1, 5, -1, 9, -1, 13, -1, 17, -1]
One can combine ternary expressions and if conditions. The ternary operator works on the filtered result:
See also: Filters, which often provide a sufficient alternative to conditional list comprehensions.
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
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.
Merging Dictionaries
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.
For example, the following code flattening a list of lists using multiple for statements:
Live Demo
In both the expanded form and the list comprehension, the outer loop (first for statement) comes first.
In addition to being more compact, the nested comprehension is also significantly faster.
Inline ifs are nested similarly, and may occur in any position after the first for:
Live Demo
For the sake of readability, however, you should consider using traditional for-loops. This is especially true when
nesting is more than 2 levels deep, and/or the logic of the comprehension is too complex. multiple nested loop list
# 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
g.next() # 4
...
g.next() # 81
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 get_objects():
"""Gets objects from an API one by one"""
while True:
yield get_next_item()
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:
filter(P, S) is almost always written clearer as [x for x in S if P(x)], and this has the huge
advantage that the most common usages involve predicates that are comparisons, e.g. x==42, and
defining a lambda for that just requires much more effort for the reader (plus the lambda is slower than
the list comprehension). Even more so for map(F, S) which becomes [F(x) for x in S]. Of course, in
many cases you'd be able to use generator expressions instead.
The following lines of code are considered "not pythonic" and will raise errors in many python linters.
Taking what we have learned from the previous quote, we can break down these filter and map expressions into
their equivalent list comprehensions; also removing the lambda functions from each - making the code more
readable in the process.
# Map
# F(x) = 2*x
# S = range(10)
[2*x for x in range(10)]
Readability becomes even more apparent when dealing with chaining functions. Where due to readability, the
results of one map or filter function should be passed as a result to the next; with simple cases, these can be
replaced with a single list comprehension. Further, we can easily tell from the list comprehension what the outcome
of our process is, where there is more cognitive load when reasoning about the chained Map & Filter process.
# List comprehension
results = [2*x for x in range(10) if x % 2 == 0]
Map
Filter
where F and P are functions which respectively transform input values and return a bool
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.
l = []
for y in [3, 4, 5]:
temp = []
for x in [1, 2, 3]:
temp.append(x + y)
l.append(temp)
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
Like nested for loops, there is no limit to how deep comprehensions can be nested.
# Two lists
>>> [(i, j) for i, j in zip(list_1, list_2)]
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
# Three lists
>>> [(i, j, k) for i, j, k in zip(list_1, list_2, list_3)]
[(1, 'a', '6'), (2, 'b', '7'), (3, 'c', '8'), (4, 'd', '9')]
# so on ...
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]
In Python, the itertools.groupby() method allows developers to group values of an iterable class based on a
specified property into another iterable set of values.
Results in
This example below is essentially the same as the one above it. The only difference is that I have changed all the
tuples to lists.
Results
Results in
Notice here that the tuple as a whole counts as one key in this list
list_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat', ('persons', 'man', 'woman'), \
'wombat', 'mongoose', 'malloo', 'camel']
c = groupby(list_things, key=lambda x: x[0])
dic = {}
for k, v in c:
dic[k] = list(v)
dic
Results in
{'c': ['camel'],
'd': ['dog', 'donkey'],
'g': ['goat'],
'm': ['mongoose', 'malloo'],
'persons': [('persons', 'man', 'woman')],
'w': ['wombat']}
Sorted Version
list_things = ['goat', 'dog', 'donkey', 'mulato', 'cow', 'cat', ('persons', 'man', 'woman'), \
'wombat', 'mongoose', 'malloo', 'camel']
sorted_list = sorted(list_things, key = lambda x: x[0])
print(sorted_list)
print()
c = groupby(sorted_list, key=lambda x: x[0])
dic = {}
for k, v in c:
dic[k] = list(v)
dic
Results in
['cow', 'cat', 'camel', 'dog', 'donkey', 'goat', 'mulato', 'mongoose', 'malloo', ('persons', 'man',
'woman'), 'wombat']
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()
Watch Today →
Chapter 25: Linked List Node
Section 25.1: Write a simple Linked List Node in python
A linked list is either:
#! /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")
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']
import heapq
Both nlargest and nsmallest functions take an optional argument (key parameter) for complicated data
structures. The following example shows the use of age property to retrieve the oldest and the youngest people
from people dictionary:
people = [
{'firstname': 'John', 'lastname': 'Doe', 'age': 30},
{'firstname': 'Jane', 'lastname': 'Doe', 'age': 25},
{'firstname': 'Janie', 'lastname': 'Doe', 'age': 10},
{'firstname': 'Jane', 'lastname': 'Roe', 'age': 22},
{'firstname': 'Johnny', 'lastname': 'Doe', 'age': 12},
{'firstname': 'John', 'lastname': 'Roe', 'age': 45}
]
import heapq
heapq.heapify(numbers)
print(numbers)
# Output: [2, 4, 10, 100, 8, 50, 32, 200, 150, 20]
heapq.heappop(numbers) # 2
print(numbers)
# Output: [4, 8, 10, 100, 20, 50, 32, 200, 150]
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")
Note: using from __future__ import print_function in Python 2 will allow users to use the print() function the
same as Python 3 code. This is only available in Python 2.6 and above.
This ensures that when code execution leaves the block the file is automatically closed.
Files can be opened in different modes. In the above example the file is opened as read-only. To open an existing
file for reading only use r. If you want to read that file as bytes use rb. To append data to an existing file use a. Use
w to create a file or overwrite any existing files of the same name. You can use r+ to open a file for both reading and
writing. The first argument of open() is the filename, the second is the mode. If mode is left blank, it will default to
r.
print(lines)
# ['tomato\n', 'pasta\n', 'garlic']
print(lines)
# ['tomato', 'pasta', 'garlic']
If the size of the file is tiny, it is safe to read the whole file contents into memory. If the file is very large it is often
better to read line-by-line or by chunks, and process the input in the same loop. To do that:
When reading files, be aware of the operating system-specific line-break characters. Although for line in
fileobj automatically strips them off, it is always safe to call strip() on the lines read, as it is shown above.
Opened files (fileobj in the above examples) always point to a specific location in the file. When they are first
opened the file handle points to the very beginning of the file, which is the position 0. The file handle can display its
current position with tell:
Upon reading all the content, the file handler's position will be pointed at the end of the file:
content = fileobj.read()
end = fileobj.tell()
print('This file was %u characters long.' % end)
# This file was 22 characters long.
fileobj.close()
You can also read any length from the file content during a given call. To do this pass an argument for read().
When read() is called with no argument it will read until the end of the file. If you pass an argument it will read that
number of bytes or characters, depending on the mode (rb and r respectively):
fileobj.close()
import sys
Be aware that sys.stdin is a stream. It means that the for-loop will only terminate when the stream has ended.
You can now pipe the output of another program into your python program as follows:
In this example cat myfile can be any unix command that outputs to stdout.
import fileinput
for line in fileinput.input():
process(line)
raw_input will wait for the user to enter text and then return the result as a string.
foo = raw_input("Put a message here that asks the user for input")
In the above example foo will store whatever input the user provides.
input will wait for the user to enter text and then return the result as a string.
foo = input("Put a message here that asks the user for input")
In the above example foo will store whatever input the user provides.
In Python 2.x, to continue a line with print, end the print statement with a comma. It will automatically add a
space.
print "Hello,",
print "World!"
# Hello, World!
In Python 3.x, the print function has an optional end parameter that is what it prints at the end of the given string.
By default it's a newline character, so equivalent to this:
If you want more control over the output, you can use sys.stdout.write:
sys.stdout.write("Hello, ")
sys.stdout.write("World!")
# Hello, World!
Watch Today →
✔ Support Vector Machines
Chapter 30: Files & Folders I/O
Parameter Details
filename the path to your file or, if the file is in the working directory, the filename of your file
access_mode a string value that determines how the file is opened
buffering an integer value used for optional line buffering
When it comes to storing, reading, or communicating data, working with the files of an operating system is both
necessary and easy with Python. Unlike other languages where file input and output requires complex reading and
writing objects, Python simplifies the process only needing commands to open, read/write and close the file. This
topic explains how Python can interface with files on the operating system.
'r' - reading mode. The default. It allows you only to read the file, not to modify it. When using this mode the
file must exist.
'w' - writing mode. It will create a new file if it does not exist, otherwise will erase the file and allow you to
write to it.
'a' - append mode. It will write data to the end of the file. It does not erase the file, and the file must exist for
this mode.
'rb' - reading mode in binary. This is similar to r except that the reading is forced in binary mode. This is
also a default choice.
'r+' - reading mode plus writing mode at the same time. This allows you to read and write into files at the
same time without having to use r and w.
'rb+' - reading and writing mode in binary. The same as r+ except the data is in binary
'wb' - writing mode in binary. The same as w except the data is in binary.
'w+' - writing and reading mode. The exact same as r+ but if the file does not exist, a new one is made.
Otherwise, the file is overwritten.
'wb+' - writing and reading mode in binary mode. The same as w+ but the data is in binary.
'ab' - appending in binary mode. Similar to a except that the data is in binary.
'a+' - appending and reading mode. Similar to w+ as it will create a new file if the file does not exist.
Otherwise, the file pointer is at the end of the file if it exists.
'ab+' - appending and reading mode in binary. The same as a+ except that the data is in binary.
r r+ w w+ a a+
Read ✔ ✔ ✘ ✔ ✘ ✔
Python 3 added a new mode for exclusive creation so that you will not accidentally truncate or overwrite and
existing file.
'x' - open for exclusive creation, will raise FileExistsError if the file already exists
'xb' - open for exclusive creation writing mode in binary. The same as x except the data is in binary.
'x+' - reading and writing mode. Similar to w+ as it will create a new file if the file does not exist. Otherwise,
will raise FileExistsError.
'xb+' - writing and reading mode. The exact same as x+ but the data is binary
x x+
Read ✘ ✔
Write ✔ ✔
Creates file ✔ ✔
Erases file ✘ ✘
Initial position Start Start
Allow one to write your file open code in a more pythonic manner:
try:
with open("fname", "r") as fout:
# Work with your open file
except FileExistsError:
# Your error handling goes here
import os.path
if os.path.isfile(fname):
with open("fname", "w") as fout:
# Work with your open file
else:
# Your error handling goes here
readline() allows for more granular control over line-by-line iteration. The example below is equivalent to the one
above:
Using the for loop iterator and readline() together is considered bad practice.
More commonly, the readlines() method is used to store an iterable collection of the file's lines:
Line 0: hello
Line 1: world
import os
for root, folders, files in os.walk(root_dir):
for filename in files:
print root, filename
root_dir can be "." to start from current directory, or any other path to start from.
If you also wish to get information about the file, you may use the more efficient method os.scandir like so:
print(content)
or, to handle closing the file manually, you can forgo with and simply call close yourself:
Keep in mind that without using a with statement, you might accidentally keep the file open in case an unexpected
exception arises like so:
If you open myfile.txt, you will see that its contents are:
Python doesn't automatically add line breaks, you need to do that manually:
Line 1
Line 2
Line 3
Line 4
Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use \n instead.
If you want to specify an encoding, you simply add the encoding parameter to the open function:
It is also possible to use the print statement to write to a file. The mechanics are different in Python 2 vs Python 3,
but the concept is the same in that you can take the output that would have gone to the screen and send it to a file
instead.
#Note: it is possible to specify the file parameter AND write to the screen
#by making sure file ends up with a None value either directly or via a variable
Unlike using the write function, the print function does automatically add line breaks.
import errno
try:
with open(path) as f:
# File exists
except IOError as e:
# Raise the exception if it is not ENOENT (No such file or directory)
if e.errno != errno.ENOENT:
raise
# No such file or directory
This will also avoid race-conditions if another process deleted the file between the check and when it is used. This
race condition could happen in the following cases:
import os
os.path.isfile('/path/to/some/file.txt')
Using pathlib:
import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
...
To check whether a given path exists or not, you can follow the above EAFP procedure, or explicitly check the path:
import os
path = "/home/myFiles/directory1"
if os.path.exists(path):
## Do stuff