0% found this document useful (0 votes)
20 views63 pages

Unit IV Data Structures

Uploaded by

Shubham Wagh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views63 pages

Unit IV Data Structures

Uploaded by

Shubham Wagh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Data Structures

⮚Lists

⮚Tuples

⮚ Sets
⮚ Dictionaries

⮚Lists as Stacks, Queues, Comprehensions

Rasika Kulkarni
Strings
� String is a collection of alphabets, words or other characters.
� It is one of the primitive data structures and are the building
blocks for data manipulation.
� Python strings are "immutable" which means they cannot be
changed after they are created.
� For string manipulation, we create new strings as we go to
represent computed values because of their immutable
property.

Rasika Kulkarni
� Python does not have a character data type, a single
character is simply a string with a length of 1
� Strings can be created simply by enclosing characters
in quotes.
� Python treats single quotes the same as double quotes.
� Creating strings is as simple as assigning a value to a
variable.

Rasika Kulkarni
Cretaing Strings
� Python uses single ,double and triple quotes.
� Single quote:
Example: str=‘Welcome to python’
� Double quote:
Example: str= “I'm a girl”

� Triple Quotes : (single/double)


Example: “””I'm a girl and I am studying in ‘TY BSc’“””

Rasika Kulkarni
Accessing characters in Python :

� Strings are just like character Arrays


� 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 :
a = “Welcome"
print(a[0])
displays first character i.e. ‘W’

Rasika Kulkarni
String Slicing
� Strings are a sequence of characters, you can access it
through slicing and indexing
� Index of string starts with zero(0)
� You can also access the characters in the opposite direction
starting from -1
� Slicing is a technique in Python that allow you to specific
element or a sub-set of elements from a container object using
their index values.
� Slicing saves you from having to write loop statements.

Rasika Kulkarni
� To access a range of characters in the String, method of slicing
is used. Slicing in a String is done by using a Slicing operator
(colon).
� Syntax:
string_variable[Start index (included): Stop index
(excluded)]
Example:
str=“welcome in TY”
str[0:]
str[:-1]
str[:]

Displays output as welcome in TY

Rasika Kulkarni
Inbuilt Functions
� upper(): Returns uppercase
a=“Hello”
print(a.upper())
� lower():returns lower case
a=“HELLO”
print(a.lower())
� strip(): removes white space from the beginning or end
a=“ Welcome in python”

Rasika Kulkarni
� replace():replaces a string with another string
a=“I live in Mumbai”
a.replace(‘I’,’you’)
� Split():returns a list where the text between the
specified separator becomes the list items.
a = "Hello, World!"
print(a.split(","))
⮚ len(): Returns length of the string
A=“Hello”
print(len(A))
Displays output as 5

Rasika Kulkarni
� capitalize():Converts the first character to upper case
� center():Returns a centered string
� count():Returns the number of times a specified value occurs
in a string
� endswith():Returns true if the string ends with the specified
value
� find():Searches the string for a specified value and returns the
position of where it was found
� index():Searches the string for a specified value and returns
the position of where it was found
� isalnum():Returns True if all characters in the string are
alphanumeric
� isalpha():Returns True if all characters in the string are in the
alphabet
� isdecimal():Returns True if all characters in the string are
decimals
Rasika Kulkarni
� isdigit() :Returns True if all characters in the string
are digits
� islower():Returns True if all characters in the string
are lower case
� isnumeric():Returns True if all characters in the
string are numeric
� isspace(): Returns True if all characters in the string
are whitespaces
� isupper(): Returns True if all characters in the
string are upper case
� startswith() :Returns true if the string starts with the
specified value

Rasika Kulkarni
String Format
� The format() method takes the passed arguments, formats
them, and places them in the string where the
placeholders {} are
� The format() method takes unlimited number of arguments,
and are placed into the respective placeholders
� Ex:

quantity = 3
itemno = 11
price = 100
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
(Explore more about format function)

Rasika Kulkarni
String Operators
� + : For Concatenation
�* :Repeats the string for as many times as specified
by x
� [] : Slice Returns the character from the index
provided at x.
� [:] :Range Slice — Returns the characters from the
range provided at x:y.
� in :Membership — Returns True if x exists in the
string. Can be multiple characters.
� not in: Membership —
Returns True if x does not exist in the string. Can be
multiple characters.
Rasika Kulkarni
Task:
1. Accept string from the user. If string is in uppercase
convert it into lowercase.
2. Accept a sentence and a text from the user .Find the
entered text is there in the sentence if yes then replace it
with new text.(Pass the sentence, text to be searched &
text to be replaced to the user defined function.
3. Traverse the given string using backword slicing.

Rasika Kulkarni
List
� A List is a kind of Collection
� A collection allows us to put many values in a single
“variable”
� A collection is nice because we can carry all many
values around in one convenient package.
� Lists are created using square brackets:

� Example:

Fruits=[‘apple’,’banana’,’grapes’]

Rasika Kulkarni
� 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.
� 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.
� The list is changeable, meaning that we can change,
add, and remove items in a list after it has been created.

Rasika Kulkarni
Basic Operations :

� How to create a list


� Traversing the list(using loop)

� Accessing individual elements from the list

� Creating empty list

� Change an element/range of elements from the list

Rasika Kulkarni
Built-in Methods :

� insert(): 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
� Syntax: insert(index, item)

� Example:

list.insert(2,’rasika’)

Rasika Kulkarni
⮚ append(): add an item to the end of the list.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.append(“grapes")
print(fruits)

⮚ extend(): To append elements from another list to the current


list.
Example:
fruits = ["apple", "banana", "cherry"]
newlist = ["mango", "pineapple", "papaya"]
fruits.extend(newlist)
print(fruits)

Rasika Kulkarni
⮚ remove() :It removes the specified item.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.remove(“apple”)

⮚ pop(): method removes the specified index.


Example:
fruits = ["apple", "banana", "cherry"]
fruits.pop(0)

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

⮚ clear() : It empties the list.


fruits.clear()
(**Note: The list still remains, but it has no content.**)

Rasika Kulkarni
Del keyword

� removes the specified index


� can also delete the list completely.
� Example:
fruits = ["apple", "banana", "cherry"]
1) del fruits[0]
2) del fruits

Rasika Kulkarni
� sort(): method that will sort the list alphanumerically,
ascending, by default:
� Example:
list1=['rasika','anant','cita']
list1.sort()
print(list1)
)

Note: to print in descending


order use-

list1.sort(reverse=True)
print(list1)

Rasika Kulkarni
� Copy():Is used to create a copy of the list
Example:
list1=['rasika','anant','cita']
list2=list1.copy()
print(list2)

Don’t use list2 = list1


Here list2 will only be a reference to list1, and
changes made in list1 will automatically also be
made in list2.

Rasika Kulkarni
� reverse(): reverses the list
Example:
list1=['rasika','anant','cita']
list1.reverse()
print(list1)

Displays output as
['cita‘, 'anant‘, 'rasika’]

Rasika Kulkarni
Tuple
� Tuples are used to store homogeneous/heterogeneous
items in a single variable.
� Tuple is one of the built-in data types in Python used to
store collections of data.
� A tuple is a collection which is ordered
and unchangeable and allow duplicate values.
� Tuples are written with round brackets.

Rasika Kulkarni
Creating Tuples:

❖ Names=(‘shyam’,’radha’,’komal’)

❖ Tocreate tuples with single item use-


Names=(‘radha’, )

❖ We can also use tuple() method to make a tuple:


Names=tuple((‘shyam’,’radha’,’komal’))
(note the double round-brackets)

Rasika Kulkarni
Accessing Items in Tuple :

� To access tuple items, use the index number, inside square brackets
Fruits = ("apple", "banana", "cherry")
print(Fruits[0])
� We can also use negative indexing means start from the end.
� In negative indexing ,-1 refers to the last item, -2 refers to the second last
item etc.
Print(Fruits[-1])
Displays last item i.e. cherry
� Use Range of Indexes to access values between the specified range
� Note that in the range start index value is included and end index value is
excluded
Print(Fruits[0:2])
Will display only (apple ,banana)

Rasika Kulkarni
Check if Item Exists

� To determine if a specified item is present in a tuple


use the in keyword:
� Example:

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


if "apple" in Fruits :
print("Yes, 'apple' is in the fruits
tuple")

Rasika Kulkarni
Unpacking a Tuple

� When we create a tuple, we normally assign values to


it. This is called "packing" a tuple:
� But, in Python, we are also allowed to extract the
values back into variables. This is called "unpacking":
fruits = ("apple", "banana", "cherry")
(a,b,c) = fruits
print(a)
print(b)
print(c)

Rasika Kulkarni
Loop Through a Tuple

� Use either for loop or while to traverse the tuple

1) fruits = ("apple", "banana", "cherry")


for x in fruits:
print(x)
2) fruits = ("apple", "banana", "cherry")
for i in range(len(fruits)):
print(fruits[i])
3) i =0
while i < len(fruits):
print(fruits[i])
i=i+1

Rasika Kulkarni
Common Tuple Oprations :

� Slicing
� Addition/Join Two Tuples :To join two or more tuples ,use
the + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
� Multiplication/Multiply Tuples :If you want to multiply the
content of a tuple a given number of times, you can use
the * operator:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)

Rasika Kulkarni
� Tuples are unchangeable, meaning that you cannot
change, add, or remove items once the tuple is created.
� But there are some ways for it.

� You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
� Add Items :Since tuples are immutable, they do not have a
build-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.
fruits = ("apple", "banana", "cherry")
y = list(fruits)
y.append("orange")
fruits = tuple(y)

Rasika Kulkarni
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:
fruits = ("apple", "banana", "cherry")
y = ("orange",)
fruits += y
print(fruits)

Rasika Kulkarni
Remove Items
� Note: You cannot remove items in a tuple.
� But if we convert the tuple into a list, remove item, and
convert it back into a tuple then it is possible

Example:
fruits = ("apple", "banana", "cherry")
y = list(fruits)
y.remove("apple")
fruits = tuple(y)

� The del keyword can delete the tuple completely:


del fruits

Rasika Kulkarni
Buit-in Functions

� count()
� index()

� len(tuple)

� type()

� tuple()

� min(a)

� max(a)

� sum(tuple)

Rasika Kulkarni
Set
� Sets are used to store multiple items in a single variable.
� A set is a collection which is unordered, unchangeable,
and unindexed.
� Duplicate values are not allowed
� The major difference is that sets, unlike lists or tuples, cannot have
multiple occurrences of the same element and store unordered
values.
� Sets are basically used to perform common math operations like
unions and intersections.

Rasika Kulkarni
Add items in the set
� add():
� fruits = {"apple", "banana", "cherry"}
fruits.add("orange“)
print(fruits)

� Update (): We can also add another set into the current
set
� fruits = {"apple", "banana", "cherry"}
newset = {"pineapple", "mango", "papaya"}
fruits.update(newset)
print(fruits)
� The object in the update() method does not have to be a
set, it can be any iterable object (tuples, lists,
dictionaries etc.).
Rasika Kulkarni
� Remove(): is used to remove an item in a set.
� Pop(): Remove the last item by using
the pop() method:
� Clear(): The clear() method empties the set:

� The del keyword will delete the set completely:

� Access items in a set :


� fruits= {"apple", "banana", "cherry"}

for x in fruits :
print(x)

Rasika Kulkarni
Join two sets
� You can use the union() method that returns a new set
containing all items from both sets, 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)

Note: Both union() and update() will exclude any


duplicate items.

Rasika Kulkarni
intersection_update()

� this method will keep only the items that are


present in both sets.
� x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.intersection_update(y)

print(x)

Rasika Kulkarni
� Copy(): returns copy of set
� fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x)
� Difference():
� Return a set that contains the items that only exist in
set x, and not in set y:
� x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
� The returned set contains items that exist only in the
first set, and not in both sets.
Rasika Kulkarni
Dictionary:
� Dictionary is used to store the data in the key: value pair
format
� It is a collection which is ordered, changeable and does not
allow duplicates.
� The dictionary can be created by using multiple key-value
pairs in curly brackets {}, and each key is separated from its
value by the colon (:)
Example: Emp = {"Id":1, "Name":"Abc",
"salary": 50000}
print(Emp)
Note: The keys of a dictionary are immutable strings
The values can be of any type like integer, strings, list,
tuples etc

Rasika Kulkarni
Dictionary:
� The built-in methods dict() can also be used to create a
dictionary
# Creating a Dictionary using dict() method
Example:Student = dict({"RollNo":1,
"Name":"Xyz","City":"Pune"})
print(Student)

Rasika Kulkarni
Accessing the Dictionary Elements:
� The keys in the dictionary are unique

� Therefore, the values can be accessed in the dictionary by


using the keys in the square brackets
print(“Student Name: ",
Example: Student["Name"])
print("Roll No: ",
Student["RollNo"])

� Using get() method: print("City: ",Student["City"])


get() method can be used to access any dictionary element at
the given key
Example
print(Emp.get("salary"
))
print(Emp.get(“name”))

Rasika Kulkarni
Dictionary:
� The keys() method allows to access all the keys in the
Dictionary
# Getting all the keys in the
dictionary
keys = Student.keys()
print(keys)

� The values() method accesses all the values in the dictionary

# Getting all the values in the


dictionary
values = Student.values()
print(values)

Rasika Kulkarni
Changing values in a Dictionary:
� Values in Dictionary can be changed using the keys

Example: #Changing values in a


Dictionary using the keys

Student["Name"] = "Abc"
print(Student)
� The update() method can also be used to update the data in
the dictionary
It takes the updated key:value pair as parameter in the
specified dictionary
# Using update() method

Student.update({"City":
"Mumbai"})
print(Student)

Rasika Kulkarni
Adding elements in a Dictionary:
� A new Data element can be added in a dictionary by simply
specifying the new key:value pair in the specified dictionary
Example:
# Adding new Data element
Student["Grade"] = "Distinction"
print(Student)

� It can also be done using the update() method:

Rasika Kulkarni
Removing elements from the Dictionary:
� The pop() method removes the element from the specified
key
# Removing element using the
Example: pop() method

Student.pop("Grade")
print(Student)

� The del keyword also removes the element at the specified


key
# Removing element using the del
keyword

del Student["City"]
print(Student)

Rasika Kulkarni
Looping through the Dictionary:
1. To print all the Keys in the dictionary
Example: # Looping to print all Keys
in a Dictionary
for i in Student:
print(i)
2. To print all the values from the dictionary
Example:
# Looping to print all
values in a Dictionary
print("The values are: ")
for i in Student:
print(Student[i])

Rasika Kulkarni
Copying a Dictionary:
� The copy() and dict() can be used to create a copy of a
dictionary
Example:
#Copying a dictionary using copy() method
S1 = Student.copy()
print(S1)

#Copying a dictionary using dict() method


S2 = dict(Student)
print(S2)

Rasika Kulkarni
� We can even access these values simultaneously using
the items() method
� It returns the respective key and value pair for each
element of the dictionary.

Rasika Kulkarni
List as stack
� Data structure organizes the storage in computers so
that we can easily access and change data.
� Stacks and Queues are the earliest data structure
defined in computer science.
� A simple Python list can act as a queue and stack as
well.

Rasika Kulkarni
Stack

� A Stack is a data structure that follows the LIFO(Last


In First Out) principle.
� To implement a stack, we need two simple operations:

� push - It adds an element to the top of the


stack.
� pop - It removes an element from the top of
the stack.

Rasika Kulkarni
Rasika Kulkarni
Operations
� Adding - It adds the items in the stack and increases
the stack size. The addition takes place at the top of the
stack.
� Deletion - It consists of two conditions, first, if no
element is present in the stack, then underflow occurs
in the stack, and second, if a stack contains some
elements, then the topmost element gets removed. It
reduces the stack size.
� Traversing - It involves visiting each element of the
stack.

Rasika Kulkarni
# Code to demonstrate Implementation of
# stack using list

x = ["Python", "C", "Android"]


x.append("Java")
x.append("C++")
print(x)
print(x.pop())
print(x)
print(x.pop())
print(x)

Rasika Kulkarni
� Queue
�A Queue follows the First-in-First-Out (FIFO)
principle.
� It is opened from both the ends hence we can easily add
elements to the back and can remove elements from the
front.

� To implement a queue, we need two simple operations:


� enqueue - It adds an element to the end of the queue.

� dequeue - It removes the element from the beginning


of the queue.

Rasika Kulkarni
Rasika Kulkarni
Rasika Kulkarni
� Operations on Queue

� Addition - It adds the element in a queue and takes


place at the rear end, i.e., at the back of the queue.
� Deletion - It consists of two conditions - If no element
is present in the queue, Underflow occurs in the queue,
or if a stack contains some elements then element
present at the front gets deleted.
� Traversing - It involves to visit each element of the
queue.

Rasika Kulkarni
# Python code to demonstrate Implementing
# Queue using list

queue = ["Amar", "Akbar", "Anthony"]


queue.append("Ram")
queue.append("Iqbal")
print(queue)

# Removes the first item


print(queue.pop(0))

print(queue)

# Removes the first item


print(queue.pop(0))

print(queue)

Rasika Kulkarni
� List Comprehensions
� A very interesting application of Lists is List
Comprehension, which provides a neat way of creating
new lists.
� These new lists are created by applying an operation on
each element of an existing list.
� It will be easy to see their impact if we first check out
how it can be done using the good old for-loops:

Rasika Kulkarni
Rasika Kulkarni

You might also like