Python Update module 4
Python Update module 4
Python Collections
A collection is similar to a basket that you can add and remove items from. In some cases, they are the same types of
items, and in others they are different. Basically, it's a storage construct that allows you to collect things.
Python offers several built-in types that fall under a vague category called collections. While there isn't a formal type
called collection in Python, there are lists, Tuples, mappings, and sets.
List
Lists in Python are a built-in type called a sequence. List are mutable and allow you to add items of the same
type or different types, making them very versatile constructs. Python lists are similar to arrays in other
languages.
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
It can have any number of items and they may be of different types (integer, float, string etc.).
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements
will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an integer. We can't
use float or other types, this will result into TypeError.
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last
item and so on.
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to
access a range, we need two index that will slice that portion from the list.
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
How to change or add elements to a list?
List are mutable, meaning, their elements can be changed.
We can use assignment operator (=) to change an item or a range of items.
# mistake values
odd = [2, 4, 6, 8]
# Output: [1, 4, 6, 8]
print(odd)
# Output: [1, 3, 5, 7]
print(odd)
We can add one item to a list using append() method or add several items using extend() method.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
my_list = ['p','r','o','b','l','e','m']
We can use remove() method to remove the given item or pop() method to remove an item at the given
index.
The pop() method removes and returns the last item if index is not provided. This helps us implement lists as
stacks (first in, last out data structure).
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: 'o'
print(my_list.pop(1))
# Output: 'm'
print(my_list.pop())
my_list.clear()
# Output: []
print(my_list)
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Some examples of Python list methods:
my_list = [3, 8, 1, 6, 0, 8, 4]
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
Python Tuple
What is tuple?
In Python programming, a tuple is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas in a list, elements can be changed.
Since, tuples are quite similiar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main
advantages:
We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar)
datatypes.
Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not
possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The
parentheses are optional but is a good practice to write it.
A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple)
# nested tuple
print(my_tuple)
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# also called tuple packing
print(my_tuple)
# Output:
#3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)
1. Indexing
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that (6, 7,...)
will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result into TypeError.
Likewise, nested tuple are accessed using nested indexing, as shown in the example below.
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
my_tuple = ('p','e','r','m','i','t')
# Output: 'p'
print(my_tuple[0])
# Output: 't'
print(my_tuple[5])
#print(my_tuple[6])
#my_tuple[2.0]
# nested tuple
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# nested index
# Output: 's'
print(n_tuple[0][3])
# nested index
# Output: 4
print(n_tuple[1][1])
p
t
s
4
Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on.
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# elements beginning to 2nd
print(my_tuple[:-7])
print(my_tuple[7:])
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself
a mutable datatype like list, its nested items can be changed.
#my_tuple[1] = 9
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
my_tuple[3][0] = 9
print(my_tuple)
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple)
We can use + operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using the * operator.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
# Repeat
print(("Repeat",) * 3)
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove
items from a tuple.
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
#del my_tuple[3]
del my_tuple
my_tuple
my_tuple = ('a','p','p','l','e',)
# Count
# Output: 2
print(my_tuple.count('p'))
# Index
# Output: 3
print(my_tuple.index('l'))
Python Strings
What is String in Python?
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though you may see
characters on your screen, internally it is stored and manipulated as a combination of 0's and 1's.
This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encoding used.
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
print(my_string)
Hello
Hello
Hello
Hello, welcome to
the world of Python
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
How to access characters in a string?
We can access individual characters using indexing and a range of characters using slicing. Index starts from
0. Trying to access a character out of index range will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result into TypeError.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in
a string by using the slicing operator (colon).
str = 'programiz'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
Using for loop we can iterate through a string. Here is an example to count the number of 'l' in a string.
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
Various built-in functions that work with sequence, works with string as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an
enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for
iteration.
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Similarly, len() returns the length (number of characters) of the string.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
Python Sets
What is a set in Python?
A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable
(which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the
built-in function set().
It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set
cannot have a mutable element, like list, set or dictionary, as its element.
# set of integers
my_set = {1, 2, 3}
print(my_set)
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
We cannot access or change an element of set using indexing or slicing. Set does not support it.
We can add single element using the add() method and multiple elements using the update() method. The
update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are
avoided.
# initialize my_set
my_set = {1,3}
print(my_set)
#my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
print(my_set)
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
A particular item can be removed from set using methods, discard() and remove().
The only difference between the two is that, while using discard() if the item does not exist in the set, it
remains unchanged. But remove() will raise an error in such condition.
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# If you uncomment line 27,
# you will get an error.
# Output: KeyError: 2
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
#my_set.remove(2)
Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# clear my_set
#Output: set()
my_set.clear()
print(my_set)
Python Dictionary
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
What is dictionary in Python?
Python dictionary is an unordered collection of items. While other compound data types have only value as
an element, a dictionary has a key: value pair.
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type (string, number or
tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
While indexing is used with other container types to access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key is not found.
# Output: Jack
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
Jack
26
Dictionary are mutable. We can add new items or change the value of existing items using assignment
operator.
If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
How to delete or remove elements from a dictionary?
We can remove a particular item in a dictionary by using the method pop(). This method removes as item
with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary.
All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# Output: {2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
# print(squares)
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
When you run the program, the output will be:
16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.