# 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
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:
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.
= 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
type() function.().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'>
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'>
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
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'>
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
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
/) operator, which always yields a floating-point number.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.
**), which groups right-to-left.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 |
----> shows the code that caused the exception.--------------------------------------------------------------------------- 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
# 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'>
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.asp1
2
3
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
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
The following are examples when the function returns the value “True”
print function displays its argument(s) as a line of text output to the screen.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
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'>
\) in a string is the escape character.\n represents the newline character escape sequence, which tells print to move the output cursor to the next line.""" or ''' (recommended """).\' escape sequence.\" escape sequence.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
\ is not the escape character because another character does not follow it.| 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. |
Python string characters can be accessed with indices
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)
You can also use negative indices. In this case, it starts on the right as -1 and ends at -N on the left:
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
# 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
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
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.
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.
For more details see the following sources
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 with 20 digits of precision to the right of the decimal point.Notice that the computer starts to print random digits in the 15th decimal place
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;
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
click below for a list of string methods * https://www.w3schools.com/python/python_strings_methods.asp
\ continuation character.print statement)—this is preferred according to the Style Guide for Python Code.input and int to prompt for and read two integer values from the user.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.
Lists are a data structure in Python that are ordered, mutable, allows indexing, and allows duplicate values.
Lists can be created in multiple ways. The list() function creates an empty list.
If a string is passed into the list() function, each character in that string will become an element in the list.
Lists are more commonly created by using square brackets, i.e. []
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
We can check if an element is in our list by using statements of the following form:
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]
To extract the first element out of our list, we use square brackets. Let’s print the first element of the list
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']
Be sure to check that the index is defined within the list or an error will arise.
--------------------------------------------------------------------------- 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
Let’s print the last element of the list.
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
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.
Because lists are mutable, it is possible to change individual elements of a list.
Lets change the third element of the list to 23. Python allows for different data types in the same list.
['car', 'truck', 23, 'bike', 'motorcycle']
We can even put a list inside a list. This is called nesting.
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.
['car', 'boat', 'truck', 'scooter', 'bike', 'motorcycle', 'skateboard']
To remove an element, use the remove() function.
['car', 'boat', 'truck', 'bike', 'motorcycle', 'skateboard']
If the element is not in the list, then remove() will raise an error.
--------------------------------------------------------------------------- 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.
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.
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.
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.
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
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.
Tuples can be created in multiple ways. The tuple() function creates an empty 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.
Tuples are more commonly created using parentheses. () creates an empty 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
Checking if an element is in a a tuple using the same syntax as lists.
Indexing and slicing tuples follow the same operational rules as lists and strings.
Use [0] to retrieve the first element of the tuple.
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.
--------------------------------------------------------------------------- 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
To print the last element of the list, use negative indexing.
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
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.
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.
--------------------------------------------------------------------------- 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
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')
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 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 is easy with the = operator. Because tuples are immutable, there are no worries about the elements in the tuple changing.
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.
Sets can be created in multiple ways. The set() function creates an empty 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.
<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
Sets also allow for the standard syntax to check for containment
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.
{'motorcycle', 'scooter', 'truck', 'car', 'skateboard', 'bike'}
You can also add different data types to sets.
{'motorcycle', 'scooter', 'truck', 'car', 23, 'skateboard', 'bike'}
Let’s try to add a list to the set
--------------------------------------------------------------------------- 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.
--------------------------------------------------------------------------- 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.
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.
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.
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.
dictionaries can be created in multiple ways. The dict() function creates an empty dictionary.
Dictionaries can also be created using bracket notation. Not to be confused with a set, {} creates an empty dictionary.
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.
Accessing the values of the dictionary can be used by providing the key to the dictionary wrapped in square brackets.
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.
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.
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.
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.
--------------------------------------------------------------------------- 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
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.
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.
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.
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.
THIS SECTION IS EXTREMELY IMPORTANT: READ CAREFULLY
Understanding the concept of “classes and objects” is completely fundamental to understanding python.
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
Objects are a particular instance of a class (i.e. a populated template** of that class)**
In python attributes and methods of an object are accessed using “.” at the end
Disclaimer: This document is not an original work. It contains content from many sources and is for educational purposes only.
Sources: