Unit 2 Notes
Unit 2 Notes
List
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types
in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with
different qualities and usage.
Lists are created using square brackets:
Example to Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length: To determine how many items a list has, use the len() function:
Example Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types : List items can be of any data type:
Example String, int and boolean data types:
type() From Python's perspective, lists are defined as objects with the data type 'list': <class
'list'>
Example What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
The list() Constructor: It is also possible to use the list() constructor when creating a new
list.
Example Using the list() constructor to make a List:
Access Items : List items are indexed and you can access them by referring to the index
number:
Example Print the second item of the list:
Negative Indexing :Negative indexing means start from the end -1 refers to the last item, -2
refers to the second last item etc.
Example Print the last item of the list:
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example Return the third, fourth, and fifth item:
Check if Item Exists : To determine if a specified item is present in a list use the in keyword.
Example Check if "apple" is present in the list:
Change Item Value To change the value of a specific item, refer to the index number:
Example Change the second item:
If you insert more items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:
If you insert less items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
o/p: ['apple', 'watermelon']
Extend List:To append elements from another list to the current list, use the extend()
method.
Example Add the elements of tropical to thislist:
The extend() method does not have to append lists, you can add any iterable object (tuples,
sets, dictionaries etc.).
Remove Specified Item: The remove() method removes the specified item.
Example Remove "banana":
Remove Specified Index: The pop() method removes the specified index.
Example Remove the second item:
If you do not specify the index, the pop() method removes the last item.
Loop Through a List: You can loop through the list items by using a for loop:
Example Print all items in the list, one by one:
Loop Through the Index Numbers: You can also loop through the list items by referring to
their index number. Use the range() and len() functions to create a suitable iterable.
Example Print all items by referring to their index number: The iterable created in the
example above is [0, 1, 2].
Looping Using List Comprehension : List Comprehension offers the shortest syntax for
looping through lists:
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
List Comprehension: List comprehension offers a shorter syntax when you want to create a
new list based on the values of an existing list.
Example: Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional
test inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Sort Descending: To sort descending, use the keyword argument reverse = True:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
output: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
Reverse Order; What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
Copy a List: You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy() print(mylist)
Example Make a copy of a list with the list() method:
Join Two Lists: There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example Join two list:
Another way to join two lists is by appending all the items from list2 into list1, one by one:
Example Append list2 into list1:
Or you can use the extend() method, where the purpose is to add elements from one list to
another list:
Example Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
output: ['a', 'b', 'c', 1, 2, 3]
Python Strings
Strings : Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function
a = "Hello, World!"
print(a[1])
output: e
for x in "banana":
print(x)
ouput
b
a
n
a
n
a
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
output: True
b = "Hello, World!"
print(b[2:5])
print(b[:5])
output: llo
Hello
Example Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Python has a set of built-in methods that you can use on strings.
Upper Case : The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case :The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Remove Whitespace :Whitespace is the space before and/or after the actual text, and very
often you want to remove this space. The strip() method removes any whitespace from the
beginning or the end:
Replace String: The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Split String: The split() method returns a list where the text between the specified separator
becomes the list items. The split() method splits the string into substrings if it finds instances
of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation : To concatenate, or combine, two strings you can use the + operator.
Example Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other
3 are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
Example Create a Set:
Set Items: Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered : Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.
Unchangeable: Set items are unchangeable, meaning that we cannot change the items after
the set has been created. Once a set is created, you cannot change its items, but you can
remove items and add new items.
Duplicates Not Allowed :Sets cannot have two items with the same value.
Example :Duplicate values will be ignored:
Access Items
You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present
in a set, by using the in keyword.
Example Loop through the set, and print the values:
Change Items : Once a set is created, you cannot change its items, but you can add new
items.Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
To add items from another set into the current set, use the update() method.
Example : Add elements from tropical into thisset:
The symmetric_difference_update() method will keep only the elements that are NOT
present in both sets.
Example Keep the items that are not present in both sets:
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered : When we say that tuples are ordered, it means that the items have a defined order,
and that order will not change.
Unchangeable : Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.
Allow Duplicates: Since tuples are indexed, they can have items with the same value:
Tuple Length: To determine how many items a tuple has, use the len() function:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
output
<class 'tuple'>
<class 'str'>
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the
tuple is created.
But there are some workarounds.
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other
ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a
list, add your item(s), and convert it back into a tuple.
Example Convert the tuple into a list, add "orange", and convert it back into a tuple:
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one
item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
Example Create a new tuple with the value "orange", and add that tuple:
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Example Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)print(yellow)print(red)
Python Dictionaries
Dictionary: Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
Example Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Length: To determine how many items a dictionary has, use the len() function:
Example Print the number of items in the dictionary:
print(len(thisdict)) : 3
print(type(thisdict)) : <class 'dict'>
Dictionary Items - Data Types, The values in dictionary items can be of any data
type,String, int, boolean, and list data types.
The dict() Constructor : It is also possible to use the dict() constructor to make a dictionary.
Example :Using the dict() method to make a dictionary:
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example : Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Output: Ford
There is also a method called get() that will give you the same result:Example Get the value
of the "model" key:
x = thisdict.get("brand")
Output: Ford
Get Keys: The keys() method will return a list of all the keys in the dictionary.
x = thisdict.keys()
output: dict_keys(['brand', 'model', 'year'])
The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
Example Add a new item to the original dictionary, and see that the keys list gets updated as
well
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
output:
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
Get Values: The values() method will return a list of all the values in the dictionary.
dict_values(['Ford', 'Mustang', 1964])
output: dict_values(['Ford', 'Mustang', 1964])
Get Items: The items() method will return each item in a dictionary, as tuples in a list.
Example Get a list of the key:value pairs
x = thisdict.items()
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Check if Key Exists: To determine if a specified key is present in a dictionary use the in
keyword:
Example: Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
output: Yes, 'model' is one of the keys in the thisdict dictionary
Change Values: You can change the value of a specific item by referring to its key name:
Example Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary: The update() method will update the dictionary with the items from the
given argument.The argument must be a dictionary, or an iterable object with key:value pairs.
Example Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Adding Items: Adding an item to the dictionary is done by using a new index key and
assigning a value to it.
Update Dictionary: The update() method will update the dictionary with the items from a
given argument. If the item does not exist, the item will be added. The argument must be a
dictionary, or an iterable object with key:value pairs.
Example :Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items: There are several methods to remove items from a dictionary:
Example : The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
output: {'brand': 'Ford', 'year': 1964}
The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):
thisdict.popitem()
print(thisdict)
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
The del keyword can also delete the dictionary completely: del thisdict
Loop Through a Dictionary: You can loop through a dictionary by using a for loop.When
looping through a dictionary, the return value are the keys of the dictionary, but there are
methods to return the values as well.
Example : Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
output:
brand
model
year
for x in thisdict:
print(thisdict[x])
output:
Ford
Mustang
1964
You can also use the values() method to return values of a dictionary:
for x in thisdict.values():
print(x)
You can use the keys() method to return the keys of a dictionary:
for x in thisdict.keys():
print(x)
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
output:
brand Ford
model Mustang
year 1964
Copy a Dictionary: You cannot copy a dictionary simply by typing dict2 = dict1, because:
dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be
made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example :Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Nested Dictionaries: A dictionary can contain dictionaries, this is called nested dictionaries.
Example Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
output: {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}
Create three dictionaries, then create one dictionary that will contain the other three
dictionaries:
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
To access items from a nested dictionary, you use the name of the dictionaries, starting with
the outer dictionary:
Example Print the name of child 2:
print(myfamily["child2"]["name"])
File Handling
The key function for working with files in Python is the open() function. The open() function
takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
The code above is the same as:
f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Open a File on the Server: Assume we have the following file, located in the same folder as
Python:
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function. The open() function returns a file object,
which has a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to specify the file path, like this:
Example Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Read Only Parts of the File :By default the read() method returns the whole text, but you can
also specify how many characters you want to return:
Example Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines: You can return one line by using the readline() method:
Example Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Example Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:
Example Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files: It is a good practice to always close the file when you are done with it.
Example Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Write to an Existing File: To write to an existing file, you must add a parameter to the open()
function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
Create a New File :To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
f = open("myfile.txt", "x")
Result: a new empty file is created!
f = open("myfile.txt", "w")
Delete a File: To delete a file, you must import the OS module, and run its os.remove()
function:
Example Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Check if File exist: To avoid getting an error, you might want to check if the file exists before
you try to delete it:
Example Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
import os
os.rmdir("myfolder")
Note: You can only remove empty folders.
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed. Without the try block,
the program will crash and raise an error:
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to execute a special
block of code for a special kind of error:
Example: Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else :You can use the else keyword to define a block of code to be executed if no errors were
raised:
Example: In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally: The finally block, if specified, will be executed regardless if the try block raises an
error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
This can be useful to close objects and clean up resources:
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
The program can continue, without leaving the file object open.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
The raise keyword is used to raise an exception. You can define what kind of error to raise,
and the text to print to the user.
Example : Raise a TypeError if x is not an integer:
x = "hello"