Unit IV Data Structures
Unit IV Data Structures
⮚Lists
⮚Tuples
⮚ Sets
⮚ Dictionaries
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”
Rasika Kulkarni
Accessing characters in Python :
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[:]
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 :
Rasika Kulkarni
Built-in Methods :
� 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)
Rasika Kulkarni
⮚ remove() :It removes the specified item.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.remove(“apple”)
(**Note: If you do not specify the index, the pop() method removes
the last item.**)
Rasika Kulkarni
Del keyword
Rasika Kulkarni
� sort(): method that will sort the list alphanumerically,
ascending, by default:
� Example:
list1=['rasika','anant','cita']
list1.sort()
print(list1)
)
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)
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’)
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
Rasika Kulkarni
Unpacking a Tuple
Rasika Kulkarni
Loop Through a Tuple
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)
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:
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:
Rasika Kulkarni
intersection_update()
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
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)
Rasika Kulkarni
Changing values in a Dictionary:
� Values in Dictionary can be changed 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)
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)
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)
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
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
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.
Rasika Kulkarni
Rasika Kulkarni
Rasika Kulkarni
� Operations on Queue
Rasika Kulkarni
# Python code to demonstrate Implementing
# Queue using list
print(queue)
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