Introduction to Python Programming

Python Data Types

  • The terms “data-structures” and “data-types” are often used interchangeably.
  • However, usually, it is helpful to think of data-structures as “boxes” or “containers” and the data-type are the objects that “fill” the boxes.

  • Data Types
    • Data-types (dtype) are the fundamental building blocks of all data. In practice, different types of data required different “building blocks”.
    • In Python, there are several important “built-in” fundamental data-types. These include:
      • Numeric Types:
        • Integers (int)(e.g., 1, -300, 56)
        • Real numbers (float) (e.g., 3.1415, 2.71)
        • Complex numbers (complex) represented as “a+bi” where i=sqrt(-1)
      • Boolean Type: (bool) (e.g. True/False)
      • Text/string (str) (e.g. “hello world”)
      • None Type: (NoneType)
      • There are also “Binary Types” (bytes, bytearray, memoryview), however, these will not be discussed in detail during the boot-camp.
    • It is also possible to build or use other data-types, however, those listed above are the “built-in” data-types that come “out of the box” with python.

  • Structures data-types:
    • These data-types can be thought of as “boxes” that we can fill with data.
    • In Python, there are several important “built-in” fundamental data-structures. These include:
      • Sequence Types: list, tuple, range
      • Mapping Types: dictionaries (dict)
      • Set Types: set, frozenset
      • Classes and objects
    • These will be discussed in more detail below

Assigning a value to a variable

  • A variable name is an identifier.

  • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

  • Mandatory rules for Python variables:

    • A variable name must start with a letter or the underscore character
    • A variable name cannot start with a number
    • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
    • Variable names are case-sensitive (age, Age, and AGE are three different variables)
  • Assigning a value to a variable binds (associates) that variable’s name to a value (similar to a key-value pair).

  • You can then use the variable’s name to access the stored value.

  • The following example creates variables x and y using the assignment symbol (=) to give them values.

    • Style note: Alway insert one space on each side of the assignment symbol = and binary operators like + to make programs more readable.

# NOTE: assignment symbol (=) is not the same as the equality operator ==
x = 2
y = 3
print(x,y)
print(x + y)

#create a new variable z from algebraic manipulation of the other two
z=x*x+y
print(z)
2 3
5
7
  • We can also assign values to several variables at once, as in the following example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Orange
Banana
Cherry

Python naming conventions

  • WHY IS THIS IMPORTANT:
    • After you graduate from Georgetown, it is very likely that you will be working on teams with many collaborators.
    • Therefore, it is extremely important that you learn to write code that is well organized, clean, well documented, and follows systematic naming conventions.
      • This is important because it is unlikely that you will last long at a job where you don’t “play nice” with the other collaborators.
      • For example, by writing sloppy or un-documented code that only you can understand.
    • Python has a predefined naming convention for various data types known as PEP8. At Georgetown you’ll be expected to follow this convention

  • PYTHON NAMING CONVENTIONS:
    • Variables
      • Use a lowercase single letter, word, or words. Separate words with underscores to improve readability.
      • e.g. x, var, my_variable
    • Constants (things that never change in code)
      • Use an uppercase single letter, word, or words. Separate words with underscores to improve readability.
      • e.g. CONSTANT, MY_CONSTANT, MY_LONG_CONSTANT
    • Functions: (discussed next week)
      • Use a lowercase word or words. Separate words by underscores to improve readability.
      • e.g. function, my_function
    • Classes (see below)
      • Start each word with a capital letter. Do not separate words with underscores. This style is called camel case.
      • e.g. Model, MyClass
    • Methods (see below)
      • Use a lowercase word or words. Separate words with underscores to improve readability.
      • e.g. class_method, method)
    • Modules (script file names)
      • Use a short, lowercase word or words. Separate words with underscores to improve readability.
      • e.g. module.py, my_module.py
    • Packages (see below)
      • Use a short, lowercase word or words. Do not separate words with underscores.
      • e.g. package, mypackage
    • source: for more see https://realpython.com/python-pep8/

  • Some of these conventions have special names:
    • Camel Case: Each word, except the first, starts with a capital letter: myVariableName
    • Pascal Case: Each word starts with a capital letter: MyVariableName
    • Snake Case: Each word is separated by an underscore character: my_variable_name
    • source: for more see: https://www.w3schools.com/python/python_variables_names.asp

The python type function

  • Each object in Python has a data-type (dtype) which indicates the kind of data it represents.
  • You can view a object’s type, with the type() function.
    • Python functions
    • A python function performs a task when you call it by writing its name, followed by parentheses ().
    • The parentheses contain the function’s argument—the data that the function needs to perform its task.
  • The type() function tells you the data-type of its argument.
    • type(x) –> return data-type of x
    • From a practical standpoint, it is an important function in Python because it can help us ensure we are maintaining the integrity or correctness of the data we are trying to represent.
  • This is because, it is very useful when debugging code.
    • Knowing an object’s data-type is the first step in determining what it does in the code

The code below defines an object x for several “built-in” data-type in Python. It then uses the type() function to print the object’s type to the screen.

#EXPLORE THE VARIOUS PYTHON TYPES
print("---------------------"); 
x = "Hello World"  #str
print("x = ",x)
print("type = ",type(x))

print("---------------------"); 
x = 20  #int
print("x = ",x)
print("type = ",type(x))

print("---------------------"); 
x = 20.5 #float 
print("x = ",x)
print("type = ",type(x))
---------------------
x =  Hello World
type =  <class 'str'>
---------------------
x =  20
type =  <class 'int'>
---------------------
x =  20.5
type =  <class 'float'>
  • The three data types in the previous example are the most commonly used. However the following are also very important.

print("---------------------"); 
x = True    #bool   
print("x = ",x)
print("type = ",type(x))

print("---------------------"); 
x = 4+1j    #complex    
print("x = ",x)
print("type = ",type(x))
---------------------
x =  True
type =  <class 'bool'>
---------------------
x =  (4+1j)
type =  <class 'complex'>
  • The following are various examples of Python data-structures that we haven’t discussed yet. However, they are covered in the more detail in the sections below.
print("---------------------"); 
x = ["apple", "banana", "cherry"]   #list   
print("x = ",x); print("type = ",type(x))

print("---------------------"); 
x = ("apple", "banana", "cherry")   #tuple
print("x = ",x,); print("   type = ",type(x))

print("---------------------"); 
x = range(6)    #range  
print("x = ",x,); print("   type = ",type(x))
print(*x)
---------------------
x =  ['apple', 'banana', 'cherry']
type =  <class 'list'>
---------------------
x =  ('apple', 'banana', 'cherry')
   type =  <class 'tuple'>
---------------------
x =  range(0, 6)
   type =  <class 'range'>
0 1 2 3 4 5
  • The following are three additional examples of data structures
print("---------------------"); 
x = {"name" : "John", "age" : 36}   #dict   
print("x = ",x,); print("   type = ",type(x))

print("---------------------"); 
x = {"apple", "banana", "cherry"}   #set    
print("x = ",x); print("type = ",type(x))

print("---------------------"); 
x = frozenset({"apple", "banana", "cherry"})    #frozenset  
print("x = ",x); print("type = ",type(x))
---------------------
x =  {'name': 'John', 'age': 36}
   type =  <class 'dict'>
---------------------
x =  {'apple', 'banana', 'cherry'}
type =  <class 'set'>
---------------------
x =  frozenset({'apple', 'banana', 'cherry'})
type =  <class 'frozenset'>

Numeric operators

Operators are used to perform operations on variables and values.

When working with numeric data (int and floats) there are several built-in algebraic operations summarized in the table below

Python operation Arithmetic operator Python expression
Addition + f + 7
Subtraction – p - c
Multiplication * b * m
Exponentiation ** x ** y
True division / x / y
Floor division // x // y
Remainder (modulo) % r % s

Description * The exponentiation (**) operator raises one value to the power of another. * To calculate the square root, use the exponent 1./2 or 0.5. * True division (/) divides a numerator by a denominator and yields a floating-point number. * Floor division (//) divides a numerator by a denominator, yielding the highest integer that’s not greater than the result. * Truncates (discards) the decimal or fractional part. * Remainder operator (%) yields the remainder after the left operand is divided by the right operand. * Dividing by zero with / or // is not allowed and results in an exception.

Python allows these operations to take place between inputs of different data types. Some computer languages do not allow this.

The following examples show the output of these operations for different combinations of data types.

print("-----INT AND INT-----") 
x=9
y=2

print("addition:",x+y)
print("subtraction:",x-y)
print("multiplication:",x*y)
print("exponentiation:",x**y)
print("square root:",x**0.5)
print("division:",x/y)
print("floor division:",x//y)
print("modulo (remainder):",x%y)
-----INT AND INT-----
addition: 11
subtraction: 7
multiplication: 18
exponentiation: 81
square root: 3.0
division: 4.5
floor division: 4
modulo (remainder): 1
  • Now let’s consider the case where one input is an integer and the other is a float
print("-----INT AND FLOAT-----") 
x=9
y=2.0

print("addition:",x+y)
print("subtraction:",x-y)
print("multiplication:",x*y)
print("exponentiation:",x**y)
print("square root:",x**0.5)
print("division:",x/y)
print("floor division:",x//y)
print("modulo (remainder):",x%y)
-----INT AND FLOAT-----
addition: 11.0
subtraction: 7.0
multiplication: 18.0
exponentiation: 81.0
square root: 3.0
division: 4.5
floor division: 4.0
modulo (remainder): 1.0
  • Noticed that the outputs in the two cases are different (all outputs are floats in the second example).

Operand output types

  • If both operands are integers, the result is an integer—except for the true-division (/) operator, which always yields a floating-point number.
  • If both operands are floating-point numbers, the result is a floating-point number.
  • Mixed-type expressions produce floating-point results.

Grouping Expressions with Parentheses

  • Order of operations: Python follows the standard order PEMDAS (please excuse my dear aunt sally)
10 * (5 + 3**2.0)
140.0
10 * 5 + 3**2.0
59.0

Operator Precedence Rules

  • Generally the same as those in algebra: > 1. Expressions in parentheses evaluate first, so parentheses may force the order of evaluation to occur in any sequence you desire. Parentheses have the highest level of precedence. In expressions with nested parentheses, such as (a / (b - c)), the expression in the innermost parentheses (that is, b - c) evaluates first. > 2. Exponentiation operations evaluate next. If an expression contains several exponentiation operations, Python applies them from right to left. > 3. Multiplication, division, and modulus operations evaluate next. If an expression contains several multiplication, true-division, floor-division, and modulus operations, Python applies them from left to right. Multiplication, division, and modulus are “on the same level of precedence.” > 4. Addition and subtraction operations evaluate last. If an expression contains several addition and subtraction operations, Python applies them from left to right. Addition and subtraction also have the same level of precedence.

  • Complete list of operators and their precedence

Operator Grouping

  • When we say that Python applies certain operators from left to right, we are referring to the operators’ grouping.
  • All Python operators of the same precedence group left-to-right except for the exponentiation operator (**), which groups right-to-left.

Redundant Parentheses

  • You can use redundant parentheses to group sub-expressions to make an expression clearer.
  • This will not result in an error, however, it is generally recommended to use as few parentheses as needed.

Augmented Assignments

Augmented Assignments are a way to abbreviate traditional assignment expressions in which the same variable name appears on the left and right of the =.

# the "=" assignment operator
x = 5
print(x)
x += 3 #same as x = x + 3
print(x)
x -= 2 #same as x = x - 2
print(x)
5
8
6

The following table provides an explanation on the commonly used augmented assignments

Augmented assignment Sample expression Explanation
+= c += 7 c = c + 7
-= d -= 4 d = d - 4
*= e *= 5 e = e * 5
**= f **= 3 f = f ** 3
/= g /= 2 g = g / 2
//= g //= 2 g = g // 2
%= h %= 9 h = h % 9

Errors, Exceptions, and Tracebacks

  • Exceptions produce tracebacks.
  • The line that begins with ----> shows the code that caused the exception.
  • The error message at the bottom of the traceback shows the exception that occurred, followed by a colon (:) and an error message with more information about the exception.`
#DIVISION BY ZERO ERROR
print(-153.0 / 0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-58f5dc428235> in <module>
      1 #DIVISION BY ZERO ERROR
----> 2 print(-153.0 / 0)

ZeroDivisionError: float division by zero
#UNDEFINED VARIABLE ERROR 
print(z1+5)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-a2589fdbd219> in <module>
      1 #UNDEFINED VARIABLE ERROR
----> 2 print(z1+5)

NameError: name 'z1' is not defined

Type casting

  • There may be times when you want to change the type on to a variable. This can be done with “casting.”
    • i.e. when you convert an object of one type to a different type
    • e.g. x=1 (int) –> x=str(x) (string)
  • Python uses dynamic typing, which means that it determines the type of the object at runtime (while executing the code).
    • Languages like C and Fortran are statically typed. Meaning the variable type cannot change once it is defined

  • Below is an example of casting in which we transform an integer into a string
# INT TO STRING 
x = 5 
print("x = ",x, type(x))

#re-assign x as type string
x = str(x)
print("x = ",x, type(x))
x =  5 <class 'int'>
x =  5 <class 'str'>
  • The following are examples of “constructor” functions. The output is the argument transformed into another data-type
  • In the first example, integers, floats, and strings are all output as integers.
x = int(1)   # x will be 1
print(x)
x = int(2.8) # y will be 2
print(x)
x = int("3") # z will be 3
print(x)
#source: https://www.w3schools.com/python/python_casting.asp
1
2
3
  • In the next example, integers, floats, and strings are all output as floats.
x = float(1)     # x will be 1.0
print(x)
x = float(2.8)   # y will be 2.8
print(x)
x = float("3")   # z will be 3.0
print(x)
x = float("4.2") # w will be 4.2
print(x)
1.0
2.8
3.0
4.2
  • In the final example, integers, floats, and strings are all output as strings.
x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'
print(x,y,z)
print(type(y))
s1 2 3.0
<class 'str'>

Booleans

  • Booleans represent one of two values: True or False.
  • Alternatively, they can be thought of as binary integers (False–>0 and True–>1)

Comparison Operators

The following are various comparison operators included with python. * “==” Equal * “!=” Not equal * “>” Greater than * “<” Less than * “>=” Greater than or equal to * “<=” Less than or equal to

In the following example use various comparison operators to compare two integers

#EXAMPLE-1: 
print("A: ",10 == 9)
print("B: ",10 != 9)
print("C: ",10 != 10)
print("D: ",10 > 9)
print("E: ",10 < 9)
print("F: ",10 >= 9)
A:  False
B:  True
C:  False
D:  True
E:  False
F:  True
  • We can also compare two boolean variables, as shown in the following example.

x=True
y=False 
print("G: ",x == y)
print("H: ",x == True)
print("I: ",x == False)
G:  False
H:  True
I:  False

The bool function

  • The bool() function allows you to evaluate any value, in return it outputs True or False
  • Almost any value is evaluated to True if it has some sort of content.
    • Any string is True, except empty strings.
    • Any number is True, except 0.
    • Any list, tuple, set, and dictionary are True, except empty ones.
  • In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, ““, the number 0, and the value None.
  • And of course the value False evaluates to False.
  • Source: https://www.w3schools.com/python/python_booleans.asp

The following are examples when the function returns the value “True”

#RETURNS TRUE
print(bool("Hello"))
print(bool(15))
True
True
  • While in the following cases it returns the value “False”
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))
False
False
False
False
False
False
False

Strings

  • As mentioned earlier, strings are one of python’s fundamental data types
  • They are very important for input/output of text, as well as, many natural language processing (NLP) tasks.
  • Therefore, we are dedicating the following section to various important aspects of the python “string” data-type

The print function

  • Python’s print function displays its argument(s) as a line of text output to the screen.
  • It can take one argument, OR several arguments separated with commas
print("NOTICE THAT YOU CAN DEFINE STRINGS WITH SINGLE OR DOUBLE QUOTES\n") 
print('A: Welcome to Python!')
print("B: Welcome to Python")
print("C: Welcome", 'to', "Python")
print("D: Welcome", 'to', "Python: the year is",2021+1,"the temperature =",76.7,"F")
#NOTICE IN THE LAST PRINT COMMAND THE ARGUMENTS ARE str, int, floats
#ALSO NOTICE THAT THE COMMA INTRODUCES A SPACE IN THE OUTPUT STRING 
NOTICE THAT YOU CAN DEFINE STRINGS WITH SINGLE OR DOUBLE QUOTES

A: Welcome to Python!
B: Welcome to Python
C: Welcome to Python
D: Welcome to Python: the year is 2022 the temperature = 76.7 F

String basics

  • The following example shows various fundamental properties of python strings.
  • They are in many ways similar to Python lists, which are discussed in more detail in a later section.
a="Hi there"
print(a)
print("01234567 = the indices of the string used for referencing characters (including spaces)")
print("a[0]=",a[0],", a[1]=",a[1],", ... a[7]=",a[7])
print("number of characters =",len(a))
print("type=",type(a))
Hi there
01234567 = the indices of the string used for referencing characters (including spaces)
a[0]= H , a[1]= i , ... a[7]= e
number of characters = 8
type= <class 'str'>

String Concatenation

  • To concatenate (combine) strings in python use the + operator.
a = "Welcome to"
b = "Python"
c = a + b
print(c)

c = a +" "+ b
print(c)

d=c+"!!!!!!!"
print(d)
Welcome toPython
Welcome to Python
Welcome to Python!!!!!!!

Newlines

  • A backslash (\) in a string is the escape character.
  • The backslash and the character immediately following it form an escape sequence.
  • \n represents the newline character escape sequence, which tells print to move the output cursor to the next line.
print('Welcome\nto\n\nPython!')
Welcome
to

Python!

Multi-line Strings

  • Multi-line strings can be delimited by """ or ''' (recommended """).
  • Used for:
    • multiline strings
      • Python stores multiline strings with embedded newline characters.
    • strings containing single or double quotes
    • docstrings—the recommended way to document the purposes of certain program components.
#THREE DOUBLE QUOTES
triple_quoted_string = """This is a triple-quoted
string that spans three lines
this is the third line
"""
print(triple_quoted_string)
This is a triple-quoted
string that spans three lines
this is the third line
#THREE SINGLE QUOTES:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Including Quotes in Strings

  • A string delimited by single quotes may include double-quote characters, but not single quotes, unless you use the \' escape sequence.
  • A string delimited by double quotes may include single quote characters, but not double quotes, unless you use the \" escape sequence.
  • Triple-quoted strings may contain both single and double quotes.
print('Display "hi" in quotes')
print('Display \'hi\' in quotes')
print("Display the name O'Brien")
print("Display \"hi\" in quotes")
print("""Display "hi" and 'bye' in quotes""")
Display "hi" in quotes
Display 'hi' in quotes
Display the name O'Brien
Display "hi" in quotes
Display "hi" and 'bye' in quotes

Ignoring a Line Break in a Long String

  • You can split a long string (or a long statement) over several lines by using the  continuation character as the last character on a line to ignore the line break.
  • In this case, \ is not the escape character because another character does not follow it.
print('this is a longer string, \
so we split it over two lines')
this is a longer string, so we split it over two lines

Other Escape Sequences

Escape sequence Description
\n Insert a newline character in a string. When the string is displayed, for each newline, move the screen cursor to the beginning of the next line.
\t Insert a horizontal tab. When the string is displayed, for each tab, move the screen cursor to the next tab stop.
\\ Insert a backslash character in a string.
\" Insert a double quote character in a string.
\' Insert a single quote character in a string.

Strings indices

  • Python string characters can be accessed with indices

    • b = “hi there”
    • b[0] ‘h’
    • b[1] ‘i’
    • b[2] ’’
    • b[3] ‘t’
    • .
    • .
    • b[7] ‘e’

  • Indexing in Python always starts from zero on the left and ends with the index N-1 on the right (where N is the length of the object)

    • (left) 0, 1 .. 7 (right)

  • You can also use negative indices. In this case, it starts on the right as -1 and ends at -N on the left:

    • (left) -8, -6 .. -1 (right)
b   = "hi there"
#      01234567

print("FIRST CHARACTER")
print("b[0] =",b[0])
print("b[-8] =",b[-8])
print("SECOND CHARACTER")
print("b[1] =",b[1])
print("b[-7] =",b[-7])
print("LAST CHARACTER:")
print("b[7] = ",b[7])
print("b[-1] = ",b[-1])
FIRST CHARACTER
b[0] = h
b[-8] = h
SECOND CHARACTER
b[1] = i
b[-7] = i
LAST CHARACTER:
b[7] =  e
b[-1] =  e

Strings slicing

  • Strings can be “sliced” using the “:” character, as shown in the next example:
print(b[:4])
print(b[0:2])
print(b[3:])
print(b[3:5])
print(b[-4:])
hi t
hi
there
th
here
  • IMPORTANT: notice how when indexing, python is always inclusive (included) on the left and exclusive (not included) on the right
    • e.g. b[0:2] includes the index 0 but excludes 2
  • These indexing and slicing rules are very important in python.
  • They also apply to lists (see below) and numpy arrays as well.

Substring Membership Operators

  • “in” operator –> Returns True if a sequence with the specified value is present in the object
  • “not in” operator –> Returns True if a sequence with the specified value is not present in the object

# Define a string variable to search
my_txt = """
We hold these truths to be self-evident, that all men are created equal, that they are endowed 
with certain unalienable Rights,that among these are Life, Liberty and the pursuit of Happiness
""" 

# We can use the python command "in" to search 
# one string for another string 
print("Let's search the following string:\n",my_txt)

print("RESULTS")
print("g" in my_txt)
print("g" not in my_txt)
print("rights" in my_txt)
print("Rights" in my_txt)
print("cat" in my_txt)
# IMPORTANT: Notice that the output is a boolean variable 
Let's search the following string:
 
We hold these truths to be self-evident, that all men are created equal, that they are endowed 
with certain unalienable Rights,that among these are Life, Liberty and the pursuit of Happiness

RESULTS
True
False
False
True
False

Modifying strings

  • In python basically, everything is an “object” (see below).
  • Strings are no different, they are simply a special type of object
  • In computer science, a “method” is a special name for a function that “acts” on an object
    • These methods act on a given object using the “.” operator (as seen below)
  • In the following examples, we show several important methods (i.e. function) that act on string objects

a = " HeLLo, WorLD! "

print("THE METHOD 'upper' ACTING ON OBJECT 'a' TO CONVERT ALL ITS' CHARACTERS TO UPPER CASE")
print(a.upper())

print("\nNOTICE THAT THE VARIABLE 'a' WASNT CHANGED")
print(a)

print("\nTHE METHOD 'lower' ACTING ON THE OBJECT 'a' TO CONVERT ALL ITS' CHARACTERS TO LOWER CASE")
b=a.lower()
print(b)
THE METHOD 'upper' ACTING ON OBJECT 'a' TO CONVERT ALL ITS' CHARACTERS TO UPPER CASE
 HELLO, WORLD! 

NOTICE THAT THE VARIABLE 'a' WASNT CHANGED
 HeLLo, WorLD! 

THE METHOD 'lower' ACTING ON THE OBJECT 'a' TO CONVERT ALL ITS' CHARACTERS TO LOWER CASE
 hello, world! 
a = " HeLLo, WorLD! "

print("\nThe strip() method removes any whitespace from the beginning or the end:")
print(a.strip())

print("\nThe replace() method replaces a string with another string:")
print(a.replace("H", "J"))

The strip() method removes any whitespace from the beginning or the end:
HeLLo, WorLD!

The replace() method replaces a string with another string:
 JeLLo, WorLD! 

print("\nThe split() method splits the string into substrings if it finds instances of the separator:")
print(a.split(",")) 
print(a.split(" ")) 

print("\nThe capitalize() converts the first character to upper case")
print("hello world".capitalize()) 

The split() method splits the string into substrings if it finds instances of the separator:
[' HeLLo', ' WorLD! ']
['', 'HeLLo,', 'WorLD!', '']

The capitalize() converts the first character to upper case
Hello world
print("\nThe count(( method returns the number of times a specified value occurs in a string")
print("hello world".count("o")) 

print("\nThe find() method Searches the string for a specified value and returns the position of where it was found")
print("hello world".find("o")) 

The count(( method returns the number of times a specified value occurs in a string
2

The find() method Searches the string for a specified value and returns the position of where it was found
4

String formatting

  • When printing, it is often important to format the printed strings in different ways

  • The following examples show instances of string formatting

print("\nThe format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:")
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:
I want 3 pieces of item 567 for 49.95 dollars.
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
For only 49.00 dollars!
  • Notice that the number of decimal places printed was specified using “.2f”

  • To use formatted string literals, begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

year = 2016
event = 'Referendum'
f'Results of the {year} {event}'
'Results of the 2016 Referendum'

Machine Precision

  • Python’s built-in floating-point numbers work well for most applications.

  • Floating-point numbers are stored in a computer using binary format.

  • They can only be represented approximately in the computer due to hardware limitations.

  • The following example demonstrates this point

amount = 112.31
print(amount)
112.31
  • The following code prints amount with 20 digits of precision to the right of the decimal point.
amount1 = 112.31
print(f'{amount1:.20f}')
112.31000000000000227374
  • Notice that the computer starts to print random digits in the 15th decimal place

    • This shows that the actual floating-point value in memory is not exactly 112.31, it’s only an approximation:

  • This is because computers have finite precision. They can only store numbers up to a certain resolution, known as “Machine precision”

  • Technically;

    • Machine precision is the smallest number epsilon such that the difference between 1 and 1 + eps is nonzero,
    • ie., it is the smallest difference between two numbers that the computer recognizes.
    • On a 32 bit computer, single precision is 2^-23 (numbers up to approximately 10^-7) while double precision is 2-52 (numbers up to approximately 10^-16)
    • Source: https://praveen.tifrbng.res.in/computing/precision

Getting Input from the User

  • Python’s built-in input function requests and obtains user input.
name = input("What's your name? ")
print(name)

#type-cast as float
value1 = float(input('Enter first number: '))
value2 = float(input('Enter second number: '))

print(value1,"+",value2,"=")
print(value1+value2)
What's your name? Mac
Mac
Enter first number: 23
Enter second number: 24
23.0 + 24.0 =
47.0

Additional information

click below for a list of string methods * https://www.w3schools.com/python/python_strings_methods.asp

Docstrings

  • The Style Guide for Python Code says each script should start with a docstring that explains the script’s purpose.
  • Often spans many lines for more complex scripts.

Blank Lines

  • Blank lines and space characters to make code easier to read.
  • Together, blank lines, space characters and tab characters are known as white space.
  • Python ignores most white space.

Splitting a Lengthy Statement Across Lines

  • Typically, you write statements on one line.
  • You may spread a lengthy statement over several lines with the \ continuation character.
  • Also can split long code lines in parentheses without using continuation characters (as in the script’s first print statement)—this is preferred according to the Style Guide for Python Code.

Reading Integer Values from the User

  • We use built-in functions input and int to prompt for and read two integer values from the user.

Garbage Collection

  • Python creates objects in memory and removes them from memory as necessary.
  • When an object is no longer bound to a variable, Python can automatically removes the object from memory.
  • This process—called garbage collection—helps ensure that memory is available for new objects.

Data Structures

In this section, we will explore 4 different built-in Python data structures that are useful in organizing and storing larger amounts of data and variables. Before learning these data structures, we will cover some necessary vocabulary.

  • Ordered: The elements in the data structure are sequential
  • Mutable: Elements in the data structure can be changed after the data structure has been created
  • Indexing: The act of extracting select elements from an ordered data structure by referencing the position(s) of the element(s)

Lists

Lists are a data structure in Python that are ordered, mutable, allows indexing, and allows duplicate values.

Creation

Lists can be created in multiple ways. The list() function creates an empty list.

myList = list()

print(type(myList))
<class 'list'>

If a string is passed into the list() function, each character in that string will become an element in the list.

myList = list("car")
print(myList)
['c', 'a', 'r']

Lists are more commonly created by using square brackets, i.e. []

myList = []

print(type(myList))
<class 'list'>

When creating a list, the elements are separated by a comma.

# create a list
myList = ["car", "truck", "scooter", "bike", "motorcycle"]

# print the list
print(myList)
['car', 'truck', 'scooter', 'bike', 'motorcycle']

We can use the len() function to see how many elements are in the list

# get the length of the list, then print it
print(len(myList))
5

Containment

We can check if an element is in our list by using statements of the following form:

"motorcycle" in myList
True
"skateboard" in myList
False

Indexing & Slicing

Indexing and Slicing are important skills that every programmer and data scientist should know. If a data structure is ordered, it is likely possible that one can extract elements from that data structure using the relative position(s) of the element(s). The syntax for indexing and slicing Python lists is similar to indexing and slicing strings in Chapter 2.4.

REMEMBER: In Python and many other languages, indexing starts at 0. Therefore, to access the first element of an ordered data structure, we use [0]

# create a list
myList = ["car", "truck", "scooter", "bike", "motorcycle"]

## Index    0       1        2          3          4

To extract the first element out of our list, we use square brackets. Let’s print the first element of the list

# index the first element of the list
myIndex = myList[0]

# then print it
print(myIndex)
car

Indexing in the form [start:stop] extracts elements from index start up to but not including stop. If more than one element is returned, it will return a list

# index the first element of the list up to but not including the third element
mySlice = myList[0:2]

# then print
print(mySlice)
['car', 'truck']
print(type(mySlice))
<class 'list'>

Be sure to check that the index is defined within the list or an error will arise.

myList[5]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-54-7d41bfdf9e2b> in <module>
----> 1 myList[5]

IndexError: list index out of range

We can also use negative numbers to index the list from the right rather than the left

# create a list
myList = ["car", "truck", "scooter", "bike", "motorcycle"]

## Index    0       1        2          3          4
## Index*  -5      -4       -3         -2         -1

Let’s print the last element of the list.

# Index the last element of the list
myIndex = myList[-1]

# then print
print(myIndex)
motorcycle

Indexing in the form [start:stop:step] extracts elements from index start up to but not including stop, skipping elements in steps of size step

# create a list
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

## index  0  1  2  3  4  5  6  7  8  9

Let’s print all the odd numbers of the list

# Slice elements at index 0 up to but not including index 10, in steps of 2
mySlice = myList[0:10:2]

# then print
print(mySlice)
[1, 3, 5, 7, 9]

Use the index statement [::-1] to return the list in reverse order.

# retrive a slice of all the elements in the list, in reverse order
mySlice = myList[::-1]

# then print
print(mySlice)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Mutating List Elements

Because lists are mutable, it is possible to change individual elements of a list.

# create a list
myList = ["car", "truck", "scooter", "bike", "motorcycle"]

## Index    0       1        2          3          4

Lets change the third element of the list to 23. Python allows for different data types in the same list.

# change the third element in myList to 23
myList[2] = 23

# then print
print(myList)
['car', 'truck', 23, 'bike', 'motorcycle']

We can even put a list inside a list. This is called nesting.

# create another list
newList = [1,2,3]

# change the last element in myList to newList
myList[-1] = newList

# then print
print(myList)
['car', 'truck', 23, 'bike', [1, 2, 3]]

Adding and Removing Elements

Python lists are dynamic, meaning they can easily change size by having elements added or removed from them.

# create a list
myList = ["car", "truck", "scooter", "bike", "motorcycle"]

# then print
print(myList)
['car', 'truck', 'scooter', 'bike', 'motorcycle']

The append() method function allows for us to add an element to the end of a list.

# Use the append function to add "skateboard" to the list
myList.append("skateboard")

# then print
print(myList)
['car', 'truck', 'scooter', 'bike', 'motorcycle', 'skateboard']

Using the insert() function, you can also add an element to a list at a specific position. This operation shifts the element currently at the index to the right.

# insert "boat" into the list at index 1
myList.insert(1, "boat")

# then print
print(myList)
['car', 'boat', 'truck', 'scooter', 'bike', 'motorcycle', 'skateboard']

To remove an element, use the remove() function.

# remove "scooter from the list"
myList.remove("scooter")

# then print
print(myList)
['car', 'boat', 'truck', 'bike', 'motorcycle', 'skateboard']

If the element is not in the list, then remove() will raise an error.

myList.remove("lasagna")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-67-1bf1eb78e068> in <module>
----> 1 myList.remove("lasagna")

ValueError: list.remove(x): x not in list
# create a list
myList = ["car", "truck", "scooter", "bike", "motorcycle"]

# then print
print(myList)
['car', 'truck', 'scooter', 'bike', 'motorcycle']

Another way to remove an element from a list is to use the pop() function. This lets a user remove an element at a specific index in the list. Note that the pop() function also returns the element that was removed from the list.

# pop the element at index 0 in the list and assign it to myItem
myItem = myList.pop(0)

# print the removed item
print(myItem, "was removed from the list\n")

# then print the list
print("The new list is now\n",myList)
car was removed from the list

The new list is now
 ['truck', 'scooter', 'bike', 'motorcycle']

If an index is not provided for the pop() method, then the last element in the list will be “popped”.

# pop the last element in the list and assign it to myItem
myItem = myList.pop()

# print the removed item
print(myItem, "was removed from the list\n")

# then print the list
print("The new list is now\n",myList)
motorcycle was removed from the list

The new list is now
 ['truck', 'scooter', 'bike']

The clear() function removes all elements in the list.

# remove all elements in the list
myList.clear()

# then print
print(myList)
[]

Joining Lists

The + operator lets us combine two or more lists into one list.

# create two lists
myList1 = ["x", "y", "z"]
myList2 = [3, 2, 1]

# join the lists, then assign to myList3
myList3 = myList1 + myList2

# then print
print(myList3)
['x', 'y', 'z', 3, 2, 1]

The extend() function performs the same task of joining two lists. This operation is done in-place, meaning that a new list is not returned. Rather the left operand list is updated to include the elements of the right operand list.

# create two lists
myList1 = ["x", "y", "z"]
myList2 = [3, 2, 1]

# add the elements of myList2 to myList1
myList1.extend(myList2)

# then print
print(myList1)
['x', 'y', 'z', 3, 2, 1]

Sorting

Sorting elements of the same data type is easy. The sort() method function sorts the elements of the list increasing order. This operation is also an in-place operation.

# create an unsorted list
myList = [4, 1, 3, 2, 6, 5]

# sort the list using the sort() method
myList.sort()

# then print
print(myList)
[1, 2, 3, 4, 5, 6]

Copying

Copying an array to a new variable uses the = assignment operator.

# create a list
myList1 = ["x", "y", "z"]

# "copy" the list to myList2
myList2 = myList1

# print the new list
print(myList2)
['x', 'y', 'z']

However, this operation creates a view of the list, not a copy. Changing the original list also changes the copied list. Because of this, using the = assignment operator is ill-advised. More information on copies vs. views will come in later lectures.

# Mutate an element of myList1
myList1[1] = 23

# print myList2
print(myList2)
['x', 23, 'z']

Instead, the copy() method function creates a true copy of the list.

# create a list
myList1 = ["x", "y", "z"]

# copy the list to myList2
myList2 = myList1.copy()

# then print
print(myList2)
['x', 'y', 'z']

By using the copy() method function,myList2 is unaffected from changes that occur to myList1

# Mutate an element of myList1
myList1[1] = 23

# print myList2
print(myList2)
['x', 'y', 'z']

Tuples

Tuples are a data structure in Python that are ordered, immutable, allows indexing, and allows duplicate values. The only top-level difference between lists and tuples in Python are that lists are mutable and tuples are immutable.

Creation

Tuples can be created in multiple ways. The tuple() function creates an empty tuple.

# create an empty tuple
myTuple = tuple()

# print the type
print(type(myTuple))
<class 'tuple'>

Similar to lists, if a string is passed into the tuple() function, each character in that string will become an element in the tuple.

# create a tuple
myTuple = tuple("car")

# then print
print(myTuple)
('c', 'a', 'r')

Tuples are more commonly created using parentheses. () creates an empty tuple.

# create an empty tuple
myTuple = ()

# print the type
print(type(myTuple))
<class 'tuple'>

Like lists, elements in tuples are separated by commas. When only one element is in a tuple, a comma must follow the element.

# create a single element tuple 
myTuple = ("car",)

# print the tuple
print(myTuple)

# print the type
print(type(myTuple))
('car',)
<class 'tuple'>

IF the comma in this declaration is not included, then the resulting object, will not be a tuple. This trailing is only required for single element tuples.

# create a tuple
myTuple = ("car")

# print the object
print(myTuple)

# print the type
print(type(myTuple))
car
<class 'str'>

Creating a tuple with more than one element does not require a trailing comma.

# create a tuple
myTuple = ("car", "truck", "scooter", "bike", "motorcycle")

# print the tuple
print(myTuple)
('car', 'truck', 'scooter', 'bike', 'motorcycle')

To check the length of a tuple, use the len() function

# retrieve the length of the tuple, then print it
print(len(myTuple))
5

Containment

Checking if an element is in a a tuple using the same syntax as lists.

"motorcycle" in myTuple
True
"skateboard" in myTuple
False

Indexing & Slicing

Indexing and slicing tuples follow the same operational rules as lists and strings.

# create a tuple
myTuple = ("car", "truck", "scooter", "bike", "motorcycle")

## Index    0        1         2        3          4

Use [0] to retrieve the first element of the tuple.

# retrive the first element of the tuple
myIndex = myTuple[0]

# then print
print(myIndex)
car

Indexing in the form [start:stop] extracts elements from index start up to but not including stop. If more than one element is returned, it will return a tuple.

# index the first element of the tuple up to but not including the third element
mySlice = myTuple[0:2]

# then print
print(mySlice)
('car', 'truck')

Be sure to check that the index is defined within the list or an error will arise.

print(myTuple[7])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-91-fcc6dc79b568> in <module>
----> 1 print(myTuple[7])

IndexError: tuple index out of range

We can also use negative numbers to index the list from the right rather than the left

# create a list
myTuple = ("car", "truck", "scooter", "bike", "motorcycle")

## Index    0       1        2          3          4
## Index*  -5      -4       -3         -2         -1

To print the last element of the list, use negative indexing.

# Index the last element of the tuple
myIndex = myTuple[-1]

# then print
print(myIndex)
motorcycle

Indexing in the form [start:stop:step] extracts elements from index start up to but not including stop, skipping elements in steps of size step

# create a tuple
myTuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

## index  0  1  2  3  4  5  6  7  8  9

Let’s print all the even numbers of the tuple

# Slice elements at index 1 up to but not including index 10, in steps of 2
mySlice = myTuple[1:10:2]

# then print
print(mySlice)
(2, 4, 6, 8, 10)

Use the index statement [::-1] to return the tuple in reverse order.

# retrive a slice of all the elements in the tuple, in reverse order
mySlice = myTuple[::-1]

# then print
print(mySlice)
(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

Immutable

Tuples are immutable, meaning elements in the tuple can not be altered.

# create a tuple
myTuple = ("car", "truck", "scooter", "bike", "motorcycle")

# then print
print(myTuple)
('car', 'truck', 'scooter', 'bike', 'motorcycle')

Let’s see what happens when we try to assign apple to the first index of the tuple.

# Try to assing "apple" to first index of the tuple
myTuple[0] = "apple"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-98-122b85a99ed7> in <module>
      1 # Try to assing "apple" to first index of the tuple
----> 2 myTuple[0] = "apple"

TypeError: 'tuple' object does not support item assignment

Updating Tuples

Tuples can be updated through creativity, but the resulting tuple will be a new tuple in a different memory address and will need to be reassigned to the named variable.

One method to accomplish this is to:

- Turn the tuple into a list
- Using the list `append()` method to add an element
- Turn the list back into a tuple
# create a tuple
myTuple = ("car", "truck", "scooter", "bike", "motorcycle")

# turn the tuple into a list
myList = list(myTuple)

# use the list.append() method to add "skateboard"
myList.append("skateboard")

# turn the list with the appended element into a tuple, then reassign to myTuple
# This is now a new tuple that also includes "skateboard"
myTuple = tuple(myList)

# print the new tuple
print(myTuple)
('car', 'truck', 'scooter', 'bike', 'motorcycle', 'skateboard')

Joining Tuples

It is easy to join tuples using the + assignment operator.

# create two tuples
myTuple1 = (1,2,3)
myTuple2 = ("car", "truck", "scooter")

# join the two tuples, then assign to new variable
myTuple3 = myTuple1 + myTuple2

# then print
print(myTuple3)
(1, 2, 3, 'car', 'truck', 'scooter')

The * operator repeats the tuple that many times.

# create a tuple
myTuple1 = (1,2,3)

# repeate the tuple 3 times, then assign to new variable
myTuple2 = myTuple1 * 3

# print new tuple
print(myTuple2)
(1, 2, 3, 1, 2, 3, 1, 2, 3)

This also provides another method to “alter” a tuple. Using slicing and the + assignment operator, we can perform the following process to replace the first element of a tuple.

- slice the tuple, removing the first element
- create a single-element tuple of the desired element to add
- join the single-element tuple and the sliced tuple
- reassign the joined tuple
# create a tuple
myTuple = ("car", "truck", "scooter", "bike", "motorcycle")

# slice the tuple, all elements in the tuple except the first element
mySlice = myTuple[1:]

# create a tuple containing an element you want to add
newTuple = ("skateboard",)

# join the single-element tuple and sliced tuple, reassigning to myTuple
# This is a new tuple because it has been reassigned
myTuple = newTuple + mySlice

# then print the tuple
print(myTuple)
('skateboard', 'truck', 'scooter', 'bike', 'motorcycle')

Unpacking

Unpacking is a process that assigns each element in a tuple to a unique variable. If a tuple of variable names of equal length is assigned a tuple, each element in the right side tuple will be assigned to the corresponding elements in the left side tuple.

# create a tuple
myTuple = ("car", "truck", "scooter")

# unpack the tuple
# The left side is a tuple of length 3
# The right side is a tuple of length 3
(myVar1, myVar2, myVar3) = myTuple

# print the variables
print(myVar1)
print(myVar2)
print(myVar3)
car
truck
scooter

Unpacking requires that the tuples be of equal length. Otherwise, an error will occur.

# create a tuple
myTuple = ("car", "truck", "scooter")

# try to unpack the tuple
# The left side is a tuple of length 2
# The right side is a tuple of length 3
(myVar1, myVar2) = myTuple
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-104-cc013ff6f9eb> in <module>
      5 # The left side is a tuple of length 2
      6 # The right side is a tuple of length 3
----> 7 (myVar1, myVar2) = myTuple

ValueError: too many values to unpack (expected 2)

Copying Tuples

Copying tuples is easy with the = operator. Because tuples are immutable, there are no worries about the elements in the tuple changing.

# create a tuple
myTuple1 = (1,2,3)

# copy the tuple
myTuple2 = myTuple1

# print the tuple
print(myTuple2)
(1, 2, 3)

Sets

Sets are a data structure in Python that are unordered, mutable, doesn’t allow indexing, and doesn’t allow duplicate values. Although sets are mutable, elements in sets must be immutable. Because sets are unordered, they cannot by indexed or sliced.

Creation

Sets can be created in multiple ways. The set() function creates an empty set.

# create a set
mySet = set()

# print the type
print(type(mySet))
<class 'set'>

Non-empty sets can be created using bracket notation

# create a non-empty set
mySet = {"car"}

# print the set
print(mySet)

# print the type
print(type(mySet))
{'car'}
<class 'set'>

However, empty sets cannot be created using bracket notation. Calling {} results in a dictionary.

# try to create an empty set using bracket notation
mySet = {}

# print type
print(type(mySet))
<class 'dict'>

Sets contain only unique values. If a set is created and has duplicate values, the duplicate values will be ignored. Also note that because sets are unordered, the order of the printed elements are more than likely not going to be in the same order as they were declared.

# create a set from elements that have duplicates
mySet = {"car", "car", "truck", "truck", "scooter", "scooter", "bike", "motorcycle"}

# print set, duplicates have been removed
print(mySet)
{'motorcycle', 'scooter', 'truck', 'car', 'bike'}

We can check the length of the set by using the len() function

# get the length of the set, then print it
print(len(mySet))
5

Containment

Sets also allow for the standard syntax to check for containment

"motorcycle" in mySet
True
"skateboard" in mySet
False

Adding Elements

The add() method function lets us add element to the set. This operation is in-place.

# create a set
mySet = {'scooter', 'car', 'motorcycle', 'bike', 'truck'}

# add "skateboard" to the set
mySet.add("skateboard")

# print the set
print(mySet)
{'motorcycle', 'scooter', 'truck', 'car', 'skateboard', 'bike'}

If an element is already in the set, then the add() method function will have no effect.

# add "car" to the set, already exists in set
mySet.add("car")

# print the set
print(mySet)
{'motorcycle', 'scooter', 'truck', 'car', 'skateboard', 'bike'}

You can also add different data types to sets.

# add a number to a string-only set
mySet.add(23)

# print the set
print(mySet)
{'motorcycle', 'scooter', 'truck', 'car', 23, 'skateboard', 'bike'}

Let’s try to add a list to the set

# create a list
myList = [1,2,3]

# try to add list to the set
mySet.add(myList)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-116-632eddc679b4> in <module>
      3 
      4 # try to add list to the set
----> 5 mySet.add(myList)

TypeError: unhashable type: 'list'

Let’s try to add a set to another set.

# create a new set
newSet = {1,2,3,4}

# try to add the new set to the set
mySet.add(newSet)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-117-27da04f63e51> in <module>
      3 
      4 # try to add the new set to the set
----> 5 mySet.add(newSet)

TypeError: unhashable type: 'set'

Why can’t we add sets or lists to sets? Each element in a set must be immutable. Because sets and lists are immutable, they cannot be added to sets. Conversely, tuples are immutable so they may be added to sets.

Let’s try to add a tuple to the set.

# create a tuple
myTuple = (1,2,3)

# add tuple to set
mySet.add(myTuple)

# print the set
print(mySet)
{'motorcycle', (1, 2, 3), 'scooter', 'truck', 'car', 23, 'skateboard', 'bike'}

If we want to add more than one element to a set at a time, the update() method function can be used. This is an in-place method.

# create two sets
mySet1 = {"car", "truck", "scooter",}
mySet2 = {"scooter", "bike", "motorcycle"}

# update mySet1 to include all the elements in mySet2
mySet1.update(mySet2)

# print the updated set
print(mySet1)
{'truck', 'car', 'motorcycle', 'scooter', 'bike'}

Removing Elements

Removing elements can be achieved using the remove() method function.

# create a set
mySet = {"car", "truck", "scooter", "bike", "motorcycle"}

# remove "bike" from the set
mySet.remove("bike")

# print the updated set
print(mySet)
{'motorcycle', 'scooter', 'truck', 'car'}

If an element is not in the set, then remove() will raise an error.

# create a set
mySet = {"car", "truck", "scooter", "bike", "motorcycle"}

# try to remove "apple"
mySet.remove("apple")
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-121-6566a6cc1e2b> in <module>
      3 
      4 # try to remove "apple"
----> 5 mySet.remove("apple")

KeyError: 'apple'

The discard() method function performs the same operation as remove(), but will not raise an error if the element is not in the set.

# create a set
mySet = {"car", "truck", "scooter", "bike", "motorcycle"}

# discard the element named "apple", if it exists
mySet.discard("apple")

# print the set
print(mySet)
{'motorcycle', 'scooter', 'truck', 'car', 'bike'}

The clear() method function removes all elements from the set.

# remove all elements from the set
mySet.clear()

# print the set
print(mySet)
set()

Set Operations

If we want to perform a set union operation, which results in a new set that contains elements that are in either of the sets, the union() method function can be used. This is the same operation as the update() method function but it is not in-place.

# create two sets
mySet1 = {1, 2, 3, 4}
mySet2 = {3, 4, 5, 6}

# perform the set union, then print the resulting set
print(mySet1.union(mySet2))
{1, 2, 3, 4, 5, 6}

A set intersection operation, which results in a new set that contains only elements that are in both of the sets, can be accomplished with the intersection() method function.

# create two sets
mySet1 = {1, 2, 3, 4}
mySet2 = {3, 4, 5, 6}

# perform the set intersection, then print the resulting set
print(mySet1.intersection(mySet2))
{3, 4}

If we want to perform a non-symmetric set difference operation, which results in a new set that contains elements that are in one set but not the other set, the union() method function can be used.

# create two sets
mySet1 = {1, 2, 3, 4}
mySet2 = {3, 4, 5, 6}

# perform the non-symmetric set difference, then print the resulting set
# this is interpreted as all elements in mySet1 that aren't is mySet2
print(mySet1.difference(mySet2))
{1, 2}

Non-symmetric set differences can also be accomplished using the - operator.

# create two sets
mySet1 = {1, 2, 3, 4}
mySet2 = {3, 4, 5, 6}

# perform the non-symmetric set difference, then print the resulting set
# this is interpreted as all elements in mySet1 that aren't is mySet2
print(mySet1 - mySet2)
{1, 2}

Dictionaries

Dictionaries are a unique data structure in Python that are ordered (As of Python 3.7), mutable, doesn’t allow indexing, and allows duplicate values but not for the keys. While lists, tuples, and sets are all collections of values in some form, dictionaries are collections of key-value pairs.

Creation

dictionaries can be created in multiple ways. The dict() function creates an empty dictionary.

# create an empty dictionary
myDict = dict()

# print the type
print(type(myDict))
<class 'dict'>

Dictionaries can also be created using bracket notation. Not to be confused with a set, {} creates an empty dictionary.

# create and empty dictionary
myDict  = {}

# print the type
print(type(myDict))
<class 'dict'>

Dictionaries are created using key-value pairs, where the key and value separated by a colon.

# create a dictionary using a key value pair
myDict  = {"KEY" : "VALUE"}

# print the dictionary
print(myDict)
{'KEY': 'VALUE'}

The keys must be unique. If two keys are the same, then the last key will be used. Different key-value pairs are separated by a comma.

# create a dictionary where two keys are the same
myDict = {"KEY": 4, "KEY": 5}

# print the dictionary, only the last key-value pair was stored
print(myDict)
{'KEY': 5}

The values of the dictionary do not have to be unique.

# create a dictionary where two values are the same
myDict = { "KEY1": 4, "KEY2": 4 }

# print the dictionary
print(myDict)
{'KEY1': 4, 'KEY2': 4}

Let’s try to create a dictionary using a list as a key.

# create a list
myList = [1,2,3]

# create a dictionary using a list as a key
myDict = { myList : "That's a list" }
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-133-8875a6f03e50> in <module>
      3 
      4 # create a dictionary using a list as a key
----> 5 myDict = { myList : "That's a list" }

TypeError: unhashable type: 'list'

Dictionaries require that the keys must be immutable. Because lists are mutable, they cannot be used as keys in a dictionary. Because tuples are immutable, they can be used as keys in dictionaries

# create a tuple
myTuple = (1,2,3)

# create a dictionary using a tuple as a key
myDict = { myTuple : "That's a tuple" }

# print the dictionary
print(myDict)
{(1, 2, 3): "That's a tuple"}

Dictionaries allow for many different data types. The only requirement is that the keys must be immutable.

# create a dictionary
myDict  = {
    "brand": "HP",
    "model": "Spectre x360",
    "year": 2020,
    "specs": ["CPU", "GPU"]
}

# print dictionary
print(myDict)
{'brand': 'HP', 'model': 'Spectre x360', 'year': 2020, 'specs': ['CPU', 'GPU']}

Accessing Elements

Accessing the values of the dictionary can be used by providing the key to the dictionary wrapped in square brackets.

# retrive the value associated with the key "model", then print it
print(myDict["model"])
Spectre x360

If the key is not defined in the dictionary, an error will be raised.

# try to retrieve the value associated with the key "KEY"
# key doesn't exist, raise an error
myDict["KEY"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-137-e5b3aded1916> in <module>
      1 # try to retrieve the value associated with the key "KEY"
      2 # key doesn't exist, raise an error
----> 3 myDict["KEY"]

KeyError: 'KEY'

The get() method function performs the same operation to retrieve a value associated with a key.

# retrive the value associated with the key "model", then print it
print(myDict.get("model"))
Spectre x360

However, the get() method function does not raise an error if the key does not exist. Instead, it returns None.

# try to retrieve the value associated with the key "KEY"
# key doesn't exist, return None
# Then print None
print(myDict.get("KEY"))
None

To look at all the keys in the dictionary, the keys() method function returns an object that contains all the keys.

# get all the keys in the dictionary, then print them
print(myDict.keys())
dict_keys(['brand', 'model', 'year', 'specs'])

Similarly, to look at all the values in the dictionary, the values() method function returns an object that contains all the values.

# get all the keys in the dictionary, then print them
print(myDict.values())
dict_values(['HP', 'Spectre x360', 2020, ['CPU', 'GPU']])

While these objects look like lists, they are not. They can not be indexed or sliced. A later lecture will explain how to individually access each of elements in these objects.

# try to index the keys object of the dictionary 
myDict.keys()[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-142-dca00fa3c9c3> in <module>
      1 # try to index the keys object of the dictionary
----> 2 myDict.keys()[0]

TypeError: 'dict_keys' object is not subscriptable

Changing Values

Dictionaries are mutable and allow for easy mutation of elements

# create a dictionary
myDict  = {
    "brand": "HP",
    "model": "Spectre x360",
    "year": 2020,
    "specs": ["CPU", "GPU"]
}

# update the value for the "year" key
myDict["year"] = 2021

# get the value associated with the "year" key, then print
print(myDict["year"])
2021

The update() method function allows one to add new key-value pairs to the dictionary. This operation is in-place.

# create a new dictionary with the key-value pairs we want to update
newDict = { "year": 1998 }

# update the key-value pairs using the key-value pairs of the new dictionary
myDict.update( newDict )

# get the value associated with the "year" key, then print
print(myDict["year"])
1998

If a key-value pair does not exist in the original dictionary, then a new key-value pair will be added.

# create a new dictionary with the key-value pairs we want to add
newDict = { "color" : "Black" }

# update the key-value pairs using the key-value pairs of the new dictionary
myDict.update( newDict)

# get the value associated with the "color" key, then print
print(myDict["color"])

# print the dictionary
print(myDict)
Black
{'brand': 'HP', 'model': 'Spectre x360', 'year': 1998, 'specs': ['CPU', 'GPU'], 'color': 'Black'}

To remove a key-value pair from a dictionary, use the pop() method function, declaring the key. The pop() method function returns the value associated with the removed key.

# create a dictionary
myDict  = {
    "brand": "HP",
    "model": "Spectre x360",
    "year": 2020,
    "specs": ["CPU", "GPU"]
}

# pop the key-value pair associated with the "brand" key
# the value associated with "brand" is returned
# assign returned value to myVal
myVal = myDict.pop("brand")

# print the key-value pair removed
print("{ brand :", myVal, "}", "was removed from the dictionary\n")

# print the dictionary
print(myDict)
{ brand : HP } was removed from the dictionary

{'model': 'Spectre x360', 'year': 2020, 'specs': ['CPU', 'GPU']}

If the key does not exist in the dictionary, then an error is raised.

# try to pop the key-value pair associated with the "apple" key
# doesn't exist, an error is raised
myDict.pop("apple")
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-147-165fc7de43ba> in <module>
      1 # try to pop the key-value pair associated with the "apple" key
      2 # doesn't exist, an error is raised
----> 3 myDict.pop("apple")

KeyError: 'apple'

To remove all key-value pairs from a dictionary, use the clear() method function.

# remove all key value pairs from the dictionary
myDict.clear()

# print the dictionary
print(myDict)
{}

Copying

Dictionaries suffer from the same issue as lists when it pertains to creating a copy using the = assignment operator.

# create a dictionary
myDict1  = {
    "brand": "HP",
    "model": "Spectre x360",
    "year": 2020,
    "specs": ["CPU", "GPU"]
}

# create a "copy" of myDict1
myDict2 = myDict1

print(myDict2)
{'brand': 'HP', 'model': 'Spectre x360', 'year': 2020, 'specs': ['CPU', 'GPU']}

Changes in myDict1 cause changes to occur in myDict2

# update a key-value pair in myDict1
myDict1["model"] = "Dell"

# get the value associated with the "model" key, then print
print(myDict2["model"])
Dell

The copy() method function again prevents this issue.

# create a dictionary
myDict1  = {
    "brand": "HP",
    "model": "Spectre x360",
    "year": 2020,
    "specs": ["CPU", "GPU"]
}

# create a copy of myDict1 and assign it to myDict2
myDict2 = myDict1.copy()

# print the copied dictionary
print(myDict2)
{'brand': 'HP', 'model': 'Spectre x360', 'year': 2020, 'specs': ['CPU', 'GPU']}

The copy() method prevents the dictionary copy from being altered by mutations in the original dictionary.

# update a key-value pair in myDict1
myDict1["model"] = "Dell"

# get the value associated with the "model" key, then print
print(myDict2["model"])
Spectre x360

Using the dict() method also allows for safe copying of dictionaries.

# create a dictionary
myDict1  = {
    "brand": "HP",
    "model": "Spectre x360",
    "year": 2020,
    "specs": ["CPU", "GPU"]
}

# create a copy of myDict1 and assign it to myDict2
myDict2 = dict(myDict1)

# print the copied dictionary
print(myDict2)
{'brand': 'HP', 'model': 'Spectre x360', 'year': 2020, 'specs': ['CPU', 'GPU']}

The dict() method prevents the dictionary copy from being altered by mutations in the original dictionary.

# update a key-value pair in myDict1
myDict1["model"] = "Dell"

# get the value associated with the "model" key, then print
print(myDict2["model"])
Spectre x360

Review

Python offers 4 built-in data structures to store collections of data. Each has unique traits that make them optimal for specific tasks. The following table can help visualize the functional differences between these data structures.

Structure Ordered Mutable Indexing Allowed Duplicates Allowed
List \(\times\) \(\times\) \(\times\) \(\times\)
Tuple \(\times\) \(\times\) \(\times\)
Set \(\times\)
Dictionary \(\times^1\) \(\times\) \(\times^2\)

\[_\text{1 As of Python version 3.7}\] \[_\text{2 Duplicates not allowed for keys}\]

Final Note: Never name a variable using a named function call. When in doubt, if the left side of an assignment operation is color-coded, then it is not a good idea to run that code.

# this is okay, List is capitalized
List = list()

# this is not okay, list is being overwritten
#### list = 4

If that code were to be run, if we would try to create a list using the list() function, it would not work as list would now an int.

Objects and Classes

  • THIS SECTION IS EXTREMELY IMPORTANT: READ CAREFULLY

  • Understanding the concept of “classes and objects” is completely fundamental to understanding python.

    • This is because Python is an object-oriented programming (OOP) language.
    • Which means that EVERYTHING in python is an object (of some python class).
    • We will not cover building python classes in detail during boot-camp (since it is an advanced topic).

  • However, we will introduce objects and classes here conceptually, because they are so fundamental.

  • So what are classes and objects?

  • Classes are “blueprints” or “templates” for building customizable data-structures

    • Think of them as “customizable” boxes that can;
        1. store data in what is known as “attributes of the class”
        • These are comparable to how Dictionaries have keys and values
        1. perform actions on themselves using functions which are known as “methods of the class”.
    • For example, if you wanted to build a custom data-structure to describe “animals” for a biology project.
      • Then you could create a python class called “animal” to store information about the different animals in the study.
      • This class would be a “template” for defining objects (see below) of the class “animal”, for example
        • Attributes of class “animal”
          • name
          • species
        • Methods of class animal
          • update_name(new_name) –> name=new_name
          • i.e. change the animal’s name with this method

      • IN SUMMARY: CLASSES ARE “EMPTY TEMPLATES” FOR DEFINING OBJECTS

  • Objects are a particular instance of a class (i.e. a populated template** of that class)**

    • For example;
      • object_1: the first instance of class “animal”
        • object_1 attributes
          • name=“luna”
          • species=“dog”
      • object_2: the second instance of class “animal”
        • object_2 attributes
          • name=“jack”
          • species=“cat”
      • You can think of the “attributes” as metadata associated with the various objects
      • Also, both objects would have access to the “update_name” method, which could be used at any time to change their name.

      • IN SUMMARY: OBJECTS ARE “POPULATED TEMPLATES” (INSTANCES) OF A PARTICULAR CLASS

  • In python attributes and methods of an object are accessed using “.” at the end

    • In the case of the previous example;
      • print(object_1.name) –> “luna”
      • print(object_1.species) –> “dog”
      • object_1.update_name(“stinky”)
      • print(object_1.name) –> “stinky”

References

Disclaimer: This document is not an original work. It contains content from many sources and is for educational purposes only.

Sources: