Some more python cheats

Home

1 Lists

list['a', 1, 18.2]

  • Is and ordered list of items
  • Mutable (can be changed after created) (add items, update items, remove items, etc.).
  • Items can be different data types
  • Can contain duplicate items

Lists are roughly analogous to arrays in other programming languages; however, a Python list can contain elements of different data types.

2 Tuples

tuple('a', 1, 18.2)

  • Immutable (cannot be changed)

Tuples function almost exactly like lists with one major difference: Immutability. tuple is immutable, which means it cannot be changed after creation.

Accessing elements via indexing works just like it does with lists, though you cannot update an element of a tuple.

>>> t = ('a', 1, 18.2) >>> t[0] is the first element, in this case the string 'a'

3 Dictionary

dict{"apples": 5, "pears": 2, "oranges": 9}

  • Unordered key-value pairs
  • Keys don’t have to be same data type
  • Values don’t have to be same data type
  • Keys are unique; must be immutable

>>> help(len) >>> help(list.append)

Dictionaries are analogous to "hashes" in some other languages. A dictionary is a data structure that stores simple key-value pairs. They make it very easy and fast to store and retrieve a value by supplying a key to be used as an index for that value.

3.1 Values:

The values in a Python dictionary can be anything, and like lists, the types don't have to be consistent.

3.2 Keys: A dictionary's keys have an important restriction w:

Whatever you want to use as a key, it has to be immutable and hash-able. This means that you could use a tuple as a key (immutable), but not a list (mutable). Also note that all of the basic data types that you learned about in Intro to Python

3.2.1 (int, float, bool, str, bytes)

These are immutable and can be used as dictionary keys.

You create a dictionary by using curly braces {}, separating a key from its value with a colon :, and separating the key-value pairs with commas.

You access and update elements using indexing; however instead of using numerical sequential index numbers, you use use the key as the index. You can add new elements simply by assigning a value to a new key.

Note: Dictionaries store "unordered" key-value pairs. In Python v3.6+ it might look like they maintain the order in which items have been added to the collection (due to an implementation detail), but maintaining order is not guaranteed and indeed is not done in versions below v3.6. If you need a dictionary collection to maintain the order of the items added to it, use the OrderedDict collection - see below.

>>> d = {"apples": 5, "pears": 2, "oranges": 9} >>> d["pears"] 2 >>> d["pears"] = 6 >>> d["bananas"] = 12 >>> d {'apples': 5, 'pears': 6, 'bananas': 12, 'oranges': 9}

There are a number of "batteries included" methods available for dictionaries

  • learn more in the Python docs.

    Learn more Learn more about the list, tuple, and dict Python data structures in the Python docs.

    Extra credit: Python has another native data structure: a set. We didn't cover it here out of an effort to keep this lab focused on providing the basic skills needed to engage with the DevNet Learning Labs that depend on this foundational lab; however, sets are powerful and probably worth you knowing that they exist and where to find out more about them.

    Next: Other Python collections

4 Collections

Collection Description
namedtuple() factory function for creating tuple subclasses with named fields
deque list-like container with fast appends and pops on either end
ChainMap dict-like class for creating a single view of multiple mappings
Counter dict subclass for counting hashable objects
OrderedDict dict subclass that remembers the order entries were added
defaultdict dict subclass that calls a factory function to supply missing values
UserDict wrapper around dictionary objects for easier dict subclassing
UserList wrapper around list objects for easier list subclassing
UserString wrapper around string objects for easier string subclassing
Table Source docs.python.org
   
from collections import OrderedDict
od = OrderedDict()
od["apples"] = 5
od["pears"] = 2
od["oranges"] = 9

od["pears"]

od["bananas"] = 12
print(od)

OrderedDict([('apples', 5), ('pears', 2), ('oranges', 9), ('bananas', 12)])

Not related but an example of using keyboard interrupt on a repetitive task:

from time import sleep
while True:
    try:
    print("Polling.")
    # Poll some resource
    sleep(1)
    except KeyboardInterrupt:
    break

5 Structure

Taken directly from DevNet Express course

#!/usr/bin/env python """Module docstring."""

import os import sys

STARTMESSAGE = "CLI Inspection Script"

location = os.path.abspath(file)

def main(*args): """My main script function.

Displays the full patch to this script, and a list of the arguments passed to the script. """ print(STARTMESSAGE) print("Script Location:", location) print("Arguments Passed:", args)

6 if name == 'main':

Every python program has a built-in variable called name that is set to the name of the program that python called to start execution.

So python can tell if the program was called natively/directly, or from another program, i.e. as a sub-routine, or module.

Example to illustrate: Create 2 modules, mod1 and mod2 as follows:

mod1.py


#!/usr/bin/env python
'''Demonstrate the way python uses __name__ and when it is __main__ .'''

print(f"   This is within mod1, and __name__ is {__name__}")
print(" .oO0Oo."*12, "\n\n")

mod2.py


#!/usr/bin/env python
'''Demonstrate the way python uses __name__ and when it is __main__ .'''

import mod1

print(f"   The is within mod2, and __name__ is {__name__}")
print(" //\  /"*6)
print(" /  \//"*6, "\n\n"

Running mod1.py gets me:

./mod1.py
 This is within mod1, and __name__ is __main__
.oO0Oo. .oO0Oo. .oO0Oo. .oO0Oo. .oO0Oo. .oO0Oo. 

Running mod2.py gets me:

 This is within mod1, and __name__ is mod1
.oO0Oo. .oO0Oo. .oO0Oo. .oO0Oo. .oO0Oo. .oO0Oo. 


  The is within mod2, and __name__ is __main__
  //\  / //\  / //\  / //\  / //\  / //\  /

this gives you control to run something ONLY if the program was run directly, and not as an imported module:

# Check to see if this file is the "__main__" script being executed
if __name__ == '__main__':
   _, *script_args = sys.argv
main(*script_args)

if __name__ == '__main__': 
    print("this was run directly")
else:
   print("this was run as an imported module")

7 Structure and Execution

When we run this script with from the Terminal, the Python interpreter will start with the first line and execute each statement in succession.

Flow: The "Shebang" Line: The first statement in many executable Python scripts isn't meant for the Python interpreter. This line tells the shell attempting to run the script what interpreter should be used to "execute" the script.

#!/usr/bin/env python The Python interpreter sees this line as a comment and ignores it.

The Module Docstring: The triple-quoted string at the beginning of this Python script is a module docstring, which serves as a built-in mechanism for documenting the purpose-of and the functionality-provided-by the module.

"""Module docstring.""" The interpreter will save this string as a special doc variable for the module.

Import Statements: Import statements import other code into your script so that you can use their functionality.

import os import sys When the interpreter encounters an import statement, it opens the module being imported and (starting with the first line of that module) executes each of the statements in that file. The contents of that module are then available to your script through the module's name, using dot-syntax, to access the variables, functions, and classes within the module.

Module constants, named by convention using all-CAPS variable names, are simple variable definitions. Nothing in the Python language makes these "constant." Their values can be changed.

As a community we recognize an all-CAPS variable name as something that we probably shouldn't change.

STARTMESSAGE = "CLI Inspection Script" The interpreter creates variables with these names and values.

Every function and class within the module will have at least "read access" to these variables as they exist at the top-level "global" scope within a module.

location = os.path.abspath(file) The interpreter creates variables with these names and values.

As the interpreter encounters new function or class definitions, it creates and stores them in memory to make them available to subsequent portions of your code.

def main(*args): """My main script function.

Displays the full patch to this script, and a list of the arguments passed to the script. """

print(STARTMESSAGE) print("Script Location:", location) print("Arguments Passed:", args)

Note that the statements within a function (or class) definition are not "executed" when they are defined. They are "loaded" and made available for future use in your script. You must call a function (supplying any needed arguments) to execute its block of statements.

The if name == 'main' Block: Some Python files could serve as both a script (to be executed) and a module (which could be imported). When a Python script is executed, it is given the internal name of main by the Python interpreter. All other modules, when they are imported by some calling script, will see their name as their own module name. This allows us to use the name variable to determine (at run time) if our Python file is being executed or imported, and we can use if-clauses like this to take actions, execute functions, etc., if our file is the one being executed.

if name == 'main': _, *scriptargs = sys.argv main(*scriptargs) If this file is the "main" script being executed, the if statement will evaluate to True and the interpreter proceeds with executing the statements inside the if-block. This allows us to parse any command line parameters, initialize any global variables, etc., and then call our script's "main" function.

Note: You can call your "main" function whatever you like. There is no special significance of the function name main().

-— string's native .format(), .split(), and .join() methods and there are more where those came from.

8 Difference between .append and .extend

8.1 append

Will add the element as a single value to the end of the list.

In [1]: list4 = [1,2,3,"fun",5]
In [2]: list4.append([3,1,4,"Cleese"])
In [3]: list4
Out[3]: [1, 2, 3, 'fun', 5, [3, 1, 4, 'Cleese']]

8.2 extend

Will add each element of the iterable as independant list entries to the list.

In [4]: list4 = [1,2,3,"fun",5]
In [5]: list4.extend([3,1,4,"Cleese"])
In [6]: list4
Out[6]: [1, 2, 3, 'fun', 5, 3, 1, 4, 'Cleese']

8.3 Home