Python Data Structure
By
Dr. Yogesh Rajput
Python Data Structures
Dr. Yogesh M. Rajput 2
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 with the print() function:
Dr. Yogesh M. Rajput 3
Assign String to a Variable
• Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:
a = "Hello"
print(a)
Dr. Yogesh M. Rajput 4
Slicing Strings
• We 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.
a = "Hello, World!"
print(a[2:5])
Note: The first character has index 0.
Dr. Yogesh M. Rajput 5
Slice From the Start
• By leaving out the start index, the range will start at the first
character:
• Get the characters from the start to position 5.
a = "Hello, World!"
print(a[:5])
Note: The first character has index 1.
Dr. Yogesh M. Rajput 6
Slice To the End
• By leaving out the end index, the range will go to the end:
• Get the characters from position 2, and all the way to the end.
a = "Hello, World!"
print(a[2:])
Note: Display from index 3.
Dr. Yogesh M. Rajput 7
String format() Method
Dr. Yogesh M. Rajput 8
String format() Method
• The format() method formats the specified value(s) and insert
them inside the string's placeholder.
• The placeholder is defined using curly brackets: {}.
• The format() method returns the formatted string.
Dr. Yogesh M. Rajput 9
The Placeholders
• The placeholders can be identified using named indexes
{price}, numbered indexes {0}, or even empty placeholders
{}.
txt1 = "My name is {fname}, I'm {age}".format(fname = “Sham", age = 26)
txt2 = "My name is {0}, I'm {1}".format(“Sham",26)
txt3 = "My name is {}, I'm {}".format(“Sham",26)
Dr. Yogesh M. Rajput 10
Example
• Use the format() method to insert numbers into strings:
age = 36
txt = "My name is Sham, and I am {}"
print(txt.format(age))
Dr. Yogesh M. Rajput 11
String upper() Method
Dr. Yogesh M. Rajput 12
String upper() Method
• The upper() method returns a string where all characters are
in upper case.
• Symbols and Numbers are ignored.
• Syntax
string.upper()
Dr. Yogesh M. Rajput 13
String upper() Method
txt = “good morning to all"
x = txt.upper()
print(x)
Dr. Yogesh M. Rajput 14
String lower() Method
Dr. Yogesh M. Rajput 15
String lower() Method
• The lower() method returns a string where all characters are
lower case.
• Symbols and Numbers are ignored.
• Syntax
string.lower()
Dr. Yogesh M. Rajput 16
String lower() Method
txt = “GOOD Morning to ALL"
x = txt.lower()
print(x)
Dr. Yogesh M. Rajput 17
String replace() Method
Dr. Yogesh M. Rajput 18
String replace() Method
• The replace() method replaces a specified phrase with another
specified phrase.
• Syntax
string.replace(oldvalue, newvalue, count)
Note: All occurrences of the specified phrase will be replaced, if
nothing else is specified (count).
Dr. Yogesh M. Rajput 19
String replace() Method
• Syntax
string.replace(oldvalue, newvalue, count)
Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old
value you want to replace. Default is all occurrences
Dr. Yogesh M. Rajput 20
String replace() Method
txt = "I like Tea"
x = txt.replace(“Tea", “Coffee")
print(x)
Dr. Yogesh M. Rajput 21
String split() Method
Dr. Yogesh M. Rajput 22
String split() Method
• The split() method splits a string into a list.
txt = "welcome to the SIG"
x = txt.split()
print(x)
Dr. Yogesh M. Rajput 23
Task
• Create a string for the welcome message and run the
following operations on it.
1. Convert string to lower case
2. Convert string to upper case
3. Replace the string
4. Split the string
Dr. Yogesh M. Rajput 24
String Concatenation
Dr. Yogesh M. Rajput 25
String Concatenation
• To concatenate, or combine, two strings you can use the +
operator.
Dr. Yogesh M. Rajput 26
String Concatenation
• To add a space between them, add var_1 " " var_2:
Dr. Yogesh M. Rajput 27
Escape Character
Dr. Yogesh M. Rajput 28
Escape Character
• To insert characters that are illegal in a string, use an escape
character.
• An escape character is a backslash \ followed by the character
you want to insert.
• An example of an illegal character is a double quote inside a
string that is surrounded by double quotes:
Dr. Yogesh M. Rajput 29
Escape Character
Dr. Yogesh M. Rajput 30
Escape Character
Dr. Yogesh M. Rajput 31
Escape Character
Code Result
\' Single Quote
\\ Backslash
\n New Line
\t Tab
\b Backspace
Dr. Yogesh M. Rajput 32
Python Lists
Dr. Yogesh M. Rajput 33
Lists
• Lists are used to store multiple items in a single variable.
• A list is a data structure in Python that is a mutable, or
changeable, ordered sequence of elements.
• Lists are created using square brackets: [ ]
• A list can have any number of items and they may be of
different types (integer, float, string, etc.).
Dr. Yogesh M. Rajput 34
Lists (Example)
thislist = ["apple", "banana", "cherry"]
print(thislist)
Dr. Yogesh M. Rajput 35
Lists
• A list can contain different data types:
• A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
print(list1)
Dr. Yogesh M. Rajput 36
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))
Dr. Yogesh M. Rajput 37
Access List Items
• List items are indexed and you can access them by referring to
the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Note: The first item has index 0.
Dr. Yogesh M. Rajput 38
Access List Items
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
• Remember that the first item is position 0,
• and note that the item in position 5 is NOT included
Dr. Yogesh M. Rajput 39
Task
• Create a list with the names of five students and display the
length and last three elements.
• Hint: len(), [1:2]
Dr. Yogesh M. Rajput 40
Sort Lists (Ascending)
• List objects have a sort() method that will sort the list.
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Dr. Yogesh M. Rajput 41
Sort Lists (Descending)
• List objects have a sort() method that will sort the list.
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Dr. Yogesh M. Rajput 42
Task
• Create a list with the marks of five students and sort the list in
ascending and descending order.
Dr. Yogesh M. Rajput 43
Add Items in List (append())
• The append() method appends an element to the end of the
list.
list.append(elmnt)
Parameter Description
elmnt Required. An element of any type (string, number, object etc.)
Dr. Yogesh M. Rajput 44
Add Items in List (append())
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(fruits)
Dr. Yogesh M. Rajput 45
Add Items in List (append())
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
print(a)
Dr. Yogesh M. Rajput 46
Task
• Write python to create a list of grocery items, add items to a
list using the append() function.
Dr. Yogesh M. Rajput 47
Add Items in List (insert())
• To insert a list item at a specified index, use the insert() method.
• The insert() method inserts an item at the specified index:
list.insert(ind,elmnt)
Parameter Description
ind Required. The specified index
elmnt Required. An element of any type (string, number, object etc.)
Dr. Yogesh M. Rajput 48
Add Items in List (insert())
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Dr. Yogesh M. Rajput 49
Remove Specified Item
• The remove() method removes the specified item.
list.remove(elmnt)
Parameter Description
elmnt Required. An list element
Dr. Yogesh M. Rajput 50
Remove Specified Item
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Dr. Yogesh M. Rajput 51
Remove Specified Index
• The pop() method removes the specified index.
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
Dr. Yogesh M. Rajput 52
Task
• Creat a list containing the days of the week (starting from
Monday to Saturday).
• Use the insert() method to add 'Sunday' to the list, and apply
the remove() method to eliminate 'Saturday' from the list.
Dr. Yogesh M. Rajput 53
Python Tuples
Dr. Yogesh M. Rajput 54
Tuples
• A tuple is a collection of objects which ordered and
immutable.
• Tuples are sequences, just like lists.
• The differences between tuples and lists are, the tuples cannot
be changed unlike lists and tuples use () parentheses,
whereas lists use square brackets.
Dr. Yogesh M. Rajput 55
Tuples
• Example:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Dr. Yogesh M. Rajput 56
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.
Dr. Yogesh M. Rajput 57
Ordered
• When we say that tuples are ordered,
it means that the items have a
defined order, and that order will
not change.
Dr. Yogesh M. Rajput 58
Unchangeable
• Tuples are unchangeable, meaning that
we cannot change, add or remove items
after the tuple has been created.
Dr. Yogesh M. Rajput 59
Allow Duplicates
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Dr. Yogesh M. Rajput 60
Tuple Length
• To determine how many items a tuple has, use the len()
function:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Dr. Yogesh M. Rajput 61
Task
• Create a two tuples for name and marks of five students and
print them with length.
Dr. Yogesh M. Rajput 62
Tuple with Different Data Types
Dr. Yogesh M. Rajput 63
Python count()
• The count() method returns the number of elements with the
specified value.
var.count(value)
Parameter Description
value Required. Any type (string, number, list,
tuple, etc.). The value to search for.
Dr. Yogesh M. Rajput 64
Python count()
Dr. Yogesh M. Rajput 65
Task
• Write a Python program to create a tuple containing the names
of five cities. Print the tuple and then determine how many
times a specific word appears using the count() method.
Dr. Yogesh M. Rajput 66
Python index()
• The index() method returns the position at the first occurrence
of the specified value.
var.index(elmnt)
Parameter Description
elmnt Required. Any type (string, number, list,
etc.). The element to search for
Dr. Yogesh M. Rajput 67
Python index()
Dr. Yogesh M. Rajput 68
Task
• Create a tuple with the days of the
week, print the tuple, and find the
index of 'Friday' using the index()
method.
Dr. Yogesh M. Rajput 69
Python Dictionaries
Dr. Yogesh M. Rajput 70
Dictionaries
• 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:
Dr. Yogesh M. Rajput 71
Dictionaries
• Example
Create and print a dictionary:
thisdict = {
"brand": “TATA",
"model": “Nexon",
"year": 2017
}
print(thisdict)
Dr. Yogesh M. Rajput 72
Task
• Create a dictionary to store the names and ages of three
people. Print the dictionary.
Dr. Yogesh M. Rajput 73
Dictionary Items
• Dictionary items are ordered, changeable, and does not
allow duplicates.
• Dictionary items are presented in key:value pairs, and can be
referred to by using the key name.
Dr. Yogesh M. Rajput 74
Dictionary Items
• Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": “TATA",
"model": “Nexon",
"year": 2017
}
print(thisdict[“brand”])
Dr. Yogesh M. Rajput 75
Ordered or Unordered?
• As of Python version 3.7, dictionaries are ordered. In Python
3.6 and earlier, dictionaries are unordered.
Dr. Yogesh M. Rajput 76
Changeable
• Dictionaries are changeable, meaning
that we can change, add or remove
items after the dictionary has been
created.
Dr. Yogesh M. Rajput 77
Duplicates Not Allowed
• Dictionaries cannot have two items with the same key:
• Duplicate values will overwrite existing values:
thisdict = {
"brand": “TATA",
"model": “Nexon",
"year": 2017,
"year": 2022
}
print(thisdict)
Dr. Yogesh M. Rajput 78
Dictionary Length
• To determine how many items a dictionary has, use the len()
function:
thisdict = {
"brand": “TATA",
"model": “Nexon",
"year": 2017
}
print(len(thisdict))
Dr. Yogesh M. Rajput 79
Task
• Create a dictionary representing
a phonebook with three names
and phone numbers, finally print
them with length.
Dr. Yogesh M. Rajput 80
Adding Items
• Adding an item to the dictionary is done by using a new index
key and assigning a value to it:
Dr. Yogesh M. Rajput 81
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.
Dr. Yogesh M. Rajput 82
Update Dictionary
• Add a color item to the dictionary by using the update()
method:
Dr. Yogesh M. Rajput 83
Task
• Organizing Grocery Lists with
Python Dictionaries: Adding and
Updating Entries.
• Add grocery item using
key:value and update().
Dr. Yogesh M. Rajput 84
Removing Items
• There are several methods to remove items from a dictionary:
1. pop()
2. popitem()
3. del Keyword
4. clear()
Dr. Yogesh M. Rajput 85
1) pop()
• The pop() method removes the item with the specified key
name:
Dr. Yogesh M. Rajput 86
2) popitem()
• The popitem() method removes the last inserted item
Dr. Yogesh M. Rajput 87
3) del
• The del keyword removes the item with the specified key
name:
Dr. Yogesh M. Rajput 88
3) del
• The del keyword can also delete the dictionary completely:
Dr. Yogesh M. Rajput 89
4) clear()
• The clear() method empties the dictionary:
Dr. Yogesh M. Rajput 90
Task Inventory
Apple 10
• Create a dictionary of items and
Banana 5
their quantities.
Orange 6
– Remove an item Orange
Grapes 20
– Remove the last item added
– Clear the entire inventory
Dr. Yogesh M. Rajput 91
Python Set
Dr. Yogesh M. Rajput 92
Set
• Sets are used to store multiple items in a single variable.
• A set is an unordered collection of items.
• Every set element is unique (no duplicates).
• Sets are written with curly brackets. {}
Dr. Yogesh M. Rajput 93
Set
• Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Dr. Yogesh M. Rajput 94
Duplicates Not Allowed
• Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Dr. Yogesh M. Rajput 95
Get the Length of a Set
• To determine how many items a set has, use the len() function.
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Dr. Yogesh M. Rajput 96
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.
Dr. Yogesh M. Rajput 97
Access Items
• Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Dr. Yogesh M. Rajput 98
Access Items
• Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
Dr. Yogesh M. Rajput 99
Task
• Create a set of ten animals and use a for loop to display each
animal's name.
• Also, check if "lion" is present in the set or not.
Dr. Yogesh M. Rajput 100
Add Items
• Once a set is created, you cannot change its items, but you
can add new items.
• To add one item to a set use the add() method.
Dr. Yogesh M. Rajput 101
Add Items
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Dr. Yogesh M. Rajput 102
Add Items
• To add items from another set into the current set, use the
update() method.
Dr. Yogesh M. Rajput 103
Add Items
• Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Dr. Yogesh M. Rajput 104
Add Any Iterable
• The object in the update() method does not have to be a set, it
can be any iterable object (tuples, lists, dictionaries etc.)
Dr. Yogesh M. Rajput 105
Add Any Iterable
• Example
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
Dr. Yogesh M. Rajput 106
Task
• Create a set for days and list for months finally merge using
update().
Dr. Yogesh M. Rajput 107
Remove Set Items
• To remove an item in a set, use the remove(), or the discard()
method.
• Example
Remove "banana" by using the remove() method:
Dr. Yogesh M. Rajput 108
Remove Set Items (remove())
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Dr. Yogesh M. Rajput 109
Remove Set Items (discard())
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Dr. Yogesh M. Rajput 110
Task
• Create a set for days and remove “Saturday” using discard().
Dr. Yogesh M. Rajput 111
Loop Items
• You can loop through the set items by using a for loop:
• Example
Loop through the set, and print the values:
Dr. Yogesh M. Rajput 112
Loop Items
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Dr. Yogesh M. Rajput 113
Task
• Create a set for month and print the elements using for loop.
Dr. Yogesh M. Rajput 114
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:
Dr. Yogesh M. Rajput 115
Join Two Sets
• Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Dr. Yogesh M. Rajput 116
Task
• Create two sets for name and roll no and combine them using
union().
Dr. Yogesh M. Rajput 117
Python Booleans
Dr. Yogesh M. Rajput 118
Python Booleans
• Booleans represent one of two values: True or False.
• In programming you often need to know if an expression is
True or False.
• When you compare two values, the expression is evaluated and
Python returns the Boolean answer:
Dr. Yogesh M. Rajput 119
Python Booleans
print(10 > 9)
print(10 == 9)
print(10 < 9)
Dr. Yogesh M. Rajput 120
Python Object
Dr. Yogesh M. Rajput 121
Python Object
• Python is an object-oriented programming language.
• Everything is in Python treated as an object, including variable,
function, list, tuple, dictionary, set, etc.
• Every object belongs to its class.
Dr. Yogesh M. Rajput 122
Python Object
• For example - An integer variable belongs to integer class.
• An object is a real-life entity.
• An object is the collection of various data and functions that
operate on those data.
Dr. Yogesh M. Rajput 123
Thank You.
Dr. Yogesh M. Rajput 124