0% found this document useful (0 votes)
43 views

Unit 2 Notes

Lists allow storing multiple items in a single variable. They are ordered, changeable sequences that can contain elements of any data type. Common list operations include accessing elements by index, slicing lists, checking if an element exists, modifying elements, adding and removing elements, looping through lists, and sorting lists.

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Unit 2 Notes

Lists allow storing multiple items in a single variable. They are ordered, changeable sequences that can contain elements of any data type. Common list operations include accessing elements by index, slicing lists, checking if an element exists, modifying elements, adding and removing elements, looping through lists, and sorting lists.

Uploaded by

arjun
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Unit -2

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:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:


Example A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]

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:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets


print(thislist)

Python Collections (Arrays)


There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.
*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

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:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

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:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])
o/p: ['cherry']

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:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])
o/p : ['cherry', 'orange', 'kiwi']
The search will start at index 2 (included) and end at index 5 (not included).

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[:4])
print(thislist[2:])
o/p: ['apple', 'banana', 'cherry', 'orange']
o/p: ['cherry', 'orange', 'kiwi', 'melon', 'mango']

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1])
o/p: ['orange', 'kiwi', 'melon']
#Negative indexing means starting from the end of the list.
#This example returns the items from index -4 (included) to index -1 (excluded)
#Remember that the last item has the index -1,

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:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
o/p: Yes, 'apple' is in the fruits list

Change Item Value To change the value of a specific item, refer to the index number:
Example Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)
o/p: ['apple', 'blackcurrant', 'cherry']

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
o/p: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']

If you insert more 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:2] = ["blackcurrant", "watermelon"]
print(thislist)
o/p: ['apple', 'blackcurrant', 'watermelon', 'cherry']

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']

Python - Add List Items


Append Items: To add an item to the end of the list, use the append() method:
Example Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)
Insert Items: To insert a new list item, without replacing any of the existing values, we can
use the insert() method. The insert() method inserts an item at the specified index:
Example Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]


thislist.insert(2, "watermelon")
print(thislist)
o/p: ['apple', 'banana', 'watermelon', 'cherry']

Extend List:To append elements from another list to the current list, use the extend()
method.
Example Add the elements of tropical to thislist:

thislist = ["apple", "banana", "cherry"]


tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
o/p: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

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":

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)
o/p: ['apple', 'cherry']

Remove Specified Index: The pop() method removes the specified index.
Example Remove the second item:

thislist = ["apple", "banana", "cherry"]


thislist.pop(1)
print(thislist)
thislist.pop()
print(thislist)
o/p: ['apple', 'cherry']
['apple']

If you do not specify the index, the pop() method removes the last item.

The del keyword also removes the specified index:


Example Remove the first item:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)
o/p ; ['banana', 'cherry']
Clear the List: The clear () method empties the list. The list still remains, but it has no
content.
Example Clear the list content:

thislist = ["apple", "banana", "cherry"]


thislist.clear()
print(thislist)
o/p : []

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:

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)
output: apple
banana
cherry

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].

thislist = ["apple", "banana", "cherry"]


for i in range(len(thislist)):
print(thislist[i])
output:
apple
banana
cherry

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)

Python - Sort Lists


Sort List Alphanumerically: List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
Example Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)
output: ['banana', 'kiwi', 'mango', 'orange', 'pineapple']

Sort the list numerically:


thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
output: [23, 50, 65, 82, 100]

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']

Example :Sort the list descending:


thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
output: [100, 82, 65, 50, 23]

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.

thislist = ["banana", "Orange", "Kiwi", "cherry"]


thislist.reverse()
print(thislist)
output: ['cherry', 'Kiwi', 'Orange', 'banana']

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:

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)

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:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
output: ['a', 'b', 'c', 1, 2, 3]

Another way to join two lists is by appending all the items from list2 into list1, one by one:
Example Append list2 into list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
output: ['a', 'b', 'c', 1, 2, 3]

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

Strings are Arrays:


Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a string
with a length of 1.
Square brackets can be used to access elements of the string.
Example :Get the character at position 1 (remember that the first character has the position
0):

a = "Hello, World!"
print(a[1])
output: e

Example : Loop through the letters in the word "banana":

for x in "banana":
print(x)
ouput
b
a
n
a
n
a

Example: The len() function returns the length of a string:


a = "Hello, World!"
print(len(a))
output: 13

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

Print only if "free" is present:


txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Check if "expensive" is NOT present in the following text:


txt = "The best things in life are free!"
print("expensive" not in txt)
Slicing: You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example Get the characters from position 2 to position 5 (not included):
Get the characters from the start to position 5 (not included):

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:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

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:

thisset = {"apple", "banana", "cherry"}


print(thisset)
output: {'banana', 'apple', 'cherry'}

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:

thisset = {"apple", "banana", "cherry", "apple"}


print(thisset)
output: {'banana', 'cherry', 'apple'}

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}


print(len(thisset))

A set with strings, integers and boolean values:


set1 = {"abc", 34, True, 40, "male"}

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:

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)

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:

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)

Remove a value in set by using the remove() method:

thisset = {"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset)

by using the discard() method:

thisset = {"apple", "banana", "cherry"}


thisset.discard("banana")
print(thisset)

The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}


thisset.clear()
print(thisset)

Join Two Sets


There are several ways to join two or more sets in Python. You can use the union() method
that returns a new set containing all items from both sets, or the update() method that inserts
all the items from one set into another:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
output: {'c', 'a', 1, 2, 'b', 3}

The update() method inserts the items in set2 into set1:


set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)

Keep ONLY the Duplicates


The intersection_update() method will keep only the items that are present in both sets.
Example : Keep the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
The intersection() method will return a new set, that only contains the items that are present
in both sets.
Example Return a set that contains the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)

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:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

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.

Example Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

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))

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.
Example One item tuple, remember the comma:

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.

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable
as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert
the list back into a tuple.
Example Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
output
("apple", "kiwi", "cherry")

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:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

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:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y
print(thistuple)

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:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Or you can delete the tuple completely:


Example The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry") #packing


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

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)

output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

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:

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)

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)

{'brand': 'Ford', 'model': 'Mustang'}

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

The clear() method empties the dictionary: thisdict.clear()

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

Print all values in the dictionary, one by one:

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)

Another way to make a copy is to use the built-in function dict():


mydict = dict(thisdict)

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"])

Python File Open


File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.

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()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Example Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())
Note: the "w" method will overwrite the entire file.

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

Example Create a file called "myfile.txt":

f = open("myfile.txt", "x")
Result: a new empty file is created!

Example :Create a new file if it does not exist:

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")

Delete Folder To delete an entire folder, use the os.rmdir() method:


Example Remove the folder "myfolder":

import os
os.rmdir("myfolder")
Note: You can only remove empty folders.

Python Try Except


 The try block lets you test a block of code for errors.
 The except block lets you handle the error.
 The else block lets you execute code when there is no error.
 The finally block lets you execute code, regardless of the result of the try- and except
blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an
error message. These exceptions can be handled using the try statement:
Example: The try block will generate an exception, because x is not defined:

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:

Example :This statement will raise an error, because x is not defined:


print(x)

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:

Example : Try to open and write to a file that is not writable:

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.

Raise an exception: As a Python developer you can choose to throw an exception if a


condition occurs. To throw (or raise) an exception, use the raise keyword.
Example :Raise an error and stop the program if x is lower than 0:

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"

if not type(x) is int:


raise TypeError("Only integers are allowed")

You might also like