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

Pyrhon 3rd Chapter

Python lists are ordered, mutable, and allow duplicate elements. Lists can contain elements of different data types. Elements are accessed using an integer index and lists provide many useful methods. Multi-dimensional lists are also supported in Python.
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)
66 views

Pyrhon 3rd Chapter

Python lists are ordered, mutable, and allow duplicate elements. Lists can contain elements of different data types. Elements are accessed using an integer index and lists provide many useful methods. Multi-dimensional lists are also supported in Python.
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/ 56

P age |1

3.1 Lists
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 and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No duplicate
members.
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.
A Python list is a sequence of data values called items or elements. A list is a linear data
structure where the elements are stored in a linear order one after the other. A list data type is
a flexible data type that can be modified according to the requirement, which makes it a
mutable data type. This means you can make updations in the already existing list as it does
not create a new list object. Python lists are similar to that of arrays in other programming
languages. The main difference is that a list is a collection of logically related variables of
different data types. This means a list is a collection of heterogeneous data items. You can
store values of different types in it, while the arrays in other programming language can hold
only one type of data. Moreover, an array is a static data structure, which means before using
it, we need to specify its size, while a list can be dynamically increased or decreased when
elements are added to or removed from it. In Python, a list is used to handle large amount of
heterogeneous data, without the need to declare many individual variables of different types.
The elements of the list are stored in the contiguous memory locations, that is, one after the
other. List elements can of any primitive data types or any sequence data types or a
combination of both. A Python list can have any number of elements or items.
Each list element can be accessed and manipulated using a list name, which is followed by a
unique index or subscript that specifies the position of the element in the list. Each element in
the list has a unique index that specifies its position. The index of the first item starts from 0,
the index of the second item is 1, and so on.
3.1.1 Advantages of a list:
A list is a data structure used in Python that provides almost all functionalities provided by
the array data structure. This section describes the advantages of a list in Python:
1. Mutable: A list is a mutable data type used in Python. By the term mutability, we mean
that we can create changes in the existing list object; we do not need to create a new object
every time we need to update the existing list.
2. Flexibility: A list offers the flexibility or scalability to the user. We can easily insert or
delete the list element at run time and a list expands and shrinks in the memory according
to the requirement. Moreover, we do not need to declare the list before using it. The list is
declared automatically when we assign values in [ ] (square brackets).

M. V. Khasne Data Structures in Python


P age |2

3. Functionality: The list data type comes with several functions that allow the user to easily
perform different set of operations instead of writing long code from scratch. You can use
dir(list_name) to get a list of all functions provided by a list.
4. Heterogeneous: One of the biggest advantages of using a list is that we can create a list of
heterogeneous elements. We can store the elements of different data types in a single list.
The elements of the different types consume memory according to the value of a particular
type stored in the list.
5. Multidimensional: We can use the list as a multidimensional data structure. With the help
of the multidimensional list, we can easily create a matrix using the list, and we can
perform different matrix operations on the list.
6. Dynamic: The list data type is dynamic in nature. This means that for using a list, we do
not need to declare the size of the list. The list consumes memory according to the
requirement. The list automatically expands when the user inputs data at run time and it
shrinks automatically when the user deletes the data at run time.
7. Easy to insert values: It is very easy to insert values in the list. Lists provide different
methods like append, insert, and extend to add elements to the list. We can take the input
from the user by the input method and using one of these methods, we can enter the
inputted values to the list.
8. Easy to display values: It is very easy to display different values stored in the list. We can
even display the values of the list without iterating over the list. To print the list in a
simple manner, we simply need to write the print statement and to pass the list object to
the print function, which we want to display.
9. Easy to use: The list data type is easy to use as compared to the other data types. It has the
ability to take the memory dynamically and offers different functions to provide an easy
way to write the code.

3.1.2 Defining Lists


The simplest method to create a list is by simply assigning a set of values to the list using the
assignment operator. It is the simplest way to create a list, but it is not used for real-time
inputs as the inputs are provided in the program by the programmer statically. The different
methods to define the list by the assignment operators are as follows:
3.1.2.1 Creation of a list by assigning values

# empty list
my_list1 = []
# list of integers
my_list2 = [1, 2, 3]
# list with mixed data types
my_list3 = [1, "Hello", 3.4]
# nested list
my_list4 = ["mouse", [8, 4, 6], ['a']]

M. V. Khasne Data Structures in Python


P age |3

3.1.2.2 Input a list from the user:


We can insert values in the list by taking inputs from the user. To get inputs from the user, we
can use different functions provided by Python. The method to input a list from the user is to
use the input() inbuilt function
 The insert() function:
The insert() function in Python inserts the elements in the list at a particular index of the
list. We can insert a single element in the list at a time with the insert function. If we want
to insert multiple elements in the list using the insert function, we need to write it in the
looping statement. The general syntax of the insert function is insert(index,value).
Example:

n=int(input("Enter the number of elements:"))


l=[]
for i in range(n):
a=int(input("Enter Value:"))
l.insert(i,a)
print("Entered List is:",l)

Output:
Enter the number of elements:5
Enter Value:1
Entered List is: [1]
Enter Value:2
Entered List is: [1, 2]
Enter Value:4
Entered List is: [1, 2, 4]
Enter Value:6
Entered List is: [1, 2, 4, 6]
Enter Value:8
Entered List is: [1, 2, 4, 6, 8]

 The split() function:


The split() function in Python breaks up a string at the specified separator and returns the
list of strings. Here, the separator is the space inserted while entering values from the
keyboard. The split() function creates a list of elements starting from the 0th index in the
list till the nth element of the input at the n-1 index. If we want to insert multiple elements
in the list using the split() function, we need to write it in the looping statement. The
general syntax of the insert function is split().
Example:

l=[int(x) for x in input("Enter Values:").split()]


print("Entered list is:",l)

M. V. Khasne Data Structures in Python


P age |4

Output:
Enter Values:1 3 5 2
Entered list is: [1, 3, 5, 2]

3.1.2.3 Creating Multi-dimensional Lists in Python


A list can hold other lists as well which can result in multi-dimensional lists. Next, we will
see how to create multi-dimensional lists, one by one.
One-dimensional Lists in Python:
init_list = [0]*3
print(init_list)
Output:
[0, 0, 0]

Two-dimensional Lists In Python:


two_dim_list = [ [0]*3 ] *3
print(two_dim_list)
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Three-dimensional Lists in Python:


thr_dim_list = [[ [0]*3 ] *3]*3
print(thr_dim_list)
Output:
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

3.1.2.4 Python List Comprehension


Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, set, dictionary etc.) using sequences which have been already
defined.
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of a list comprehension:
output_list = [output_exp for var in input_list if (var satisfies this condition)]
Python List comprehension helps in constructing lists in a completely natural and easy way.
List = [1,2,3,4,5]
List1 = [ i for i in range(5)]
print(List1)
Output:
[0, 1, 2, 3, 4]

M. V. Khasne Data Structures in Python


P age |5

Complicated Python List Comprehension Examples


Example 1:
print ([a+b for a in 'mug' for b in 'lid'])
Output:
[‘ml’, ‘mi’, ‘md’, ‘ul’, ‘ui’, ‘ud’, ‘gl’, ‘gi’, ‘gd’]

Example 2:
list_fruit = ["Apple","Mango","Banana","Avocado"]
first_letters = [ fruits[0] for fruits in list_fruit ]
print(first_letters)
Output:
[‘A’, ‘M’, ‘B’, ‘A’]

3.1.2.5 Deriving from another List


Suppose there is an existing list,
>>> myList1 = ['first', 'second', 'third', 'fourth', 'fifth']
And now you want to create a new list which consists some or all the elements of myList1,
then you can you do a direct assignment for complete copying of elements or use slicing, and
take only some elements.
For complete copying,
>>> myList2 = myList1
Use slicing, for copying only the first three elements,
>>> myList2 = myList1[0:3]

Adding Serial Numbers in a List


Suppose you want to add serial whole numbers (i.e., 0, 1, 2, 3, ...) into your list and just don't
want to write all of them one by one, do not worry, there is a shortcut for doing this.
For storing 0 to (n-1) numbers in a list use range(n) function.
>>> myList1 = list(range(9))
This will create a list with numbers 0 to 8 inside it.
>>> myList1 = list(range(5, 9))
This will create a list having numbers 5, 6, 7, 8

Suppose you want to create a list with squares of all whole numbers. Although there exists
various programming approaches for this problem but here is a one line method in python.
We will be introducing something new, so it can get a little tricky.
>>> myQuickList = [x**2 for x in range(5)]
The final list will contain elements like [0, 1, 4, 9, 16], i.e. x**2 where x is varying
from 0 to (5-1).

M. V. Khasne Data Structures in Python


P age |6

3.1.3 Accessing Values in a List


3.1.3.1 Accessing list elements by using Index Numbers:
Individual elements in a list can be accessed using an index in square brackets.
This is exactly analogous to accessing individual characters in a string. List
indexing is zero-based as it is with strings.
Consider the following list:
>>> a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']

The indices for the elements in a are shown below:

List Indices

Here is Python code to access some elements of a:


>>> a[0]
'foo'
>>> a[2]
'baz'
>>> a[5]
'corge'

3.1.3.2 Negative List Indexing:


Virtually everything about string indexing works similarly for lists. For example, a negative
list index counts from the end of the list:

Negative List Indexing


>>> a[-1]
'corge'
>>> a[-2]
'quux'
>>> a[-5]
'bar'

3.1.3.3 Accessing Multidimensional List:


number_sets = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(number_sets[1])

M. V. Khasne Data Structures in Python


P age |7

The second list of numbers will print out. In order to access those lower elements, you need
to use a second set of square brackets. In the first set of square brackets, specifies the top
level element that you want to access.

In the example below, that is the first list. Then, in the second set of brackets, specifies the
element within that initial top level element that you want. In that same example, it's the
second element, or the number "4."
number_sets = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(number_sets[0][1])

3.1.3.4 Accessing all elements of the list at once


Accessing all elements from the particular list at once allow the user to access all the values
from the list. This is possible by writing the list name in the print statement. The following
program demonstrates how to get values from the list:
x=int(input("Enter the ending range of the list: "))
l=list(range(x))
print("Values in the list are: ",l)

Output:
Enter the ending range of the list:5
Values in the list are: [0, 1, 2, 3, 4]

3.1.4 Deleting Values in a List


In Python, use list methods clear() , pop() , and remove() to remove items from a list. It
is also possible to delete items using del statement by specifying a position or range with an
index or slice.
 Remove all items: clear()
 Remove an item by index and get its value: pop()
 Remove an item by value: remove()
 Remove items by index or slice: del

 Remove all items: clear()


You can remove all items from the list with clear().
>>>l = list(range(10))
>>>print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>l.clear()
>>>print(l)
[]

 Remove an item by index and get its value: pop()


You can remove the item at the specified position and get the value of that item
with pop().

M. V. Khasne Data Structures in Python


P age |8

The index at the beginning is 0.


>>>print(l.pop(0))
0

>>>print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>>print(l.pop(3))
4

>>>print(l)
[1, 2, 3, 5, 6, 7, 8, 9]

You can use negative values to specify the position from the end. The index at the end
is -1.
>>>print(l.pop(-2))
8

>>>print(l)
[1, 2, 3, 5, 6, 7, 9]

If the argument is omitted, the last item is deleted.


>>>print(l.pop())
9

>>>print(l)
[1, 2, 3, 5, 6, 7]

 Remove an item by value: remove()


You can remove the first item from the list where its value is equal to the specified value
with remove().
>>>l = list('abcdefg')
>>>print(l)
['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>>l.remove('d')
>>>print(l)
['a', 'b', 'c', 'e', 'f', 'g']

 Remove items by index or slice: del


clear(), pop() and remove() are methods of list, but you can also remove
elements from a list with del statements.
Specify the item to be deleted by index. The first index is 0, and the last index is -1.
>>>l = list(range(10))
>>>print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

M. V. Khasne Data Structures in Python


P age |9

>>>del l[0]
>>>print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>>del l[-1]
>>>print(l)
[1, 2, 3, 4, 5, 6, 7, 8]

>>>del l[6]
>>>print(l)
[1, 2, 3, 4, 5, 6, 8]

Using slice, you can delete multiple items at once.


>>>l = list(range(10))
>>>print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>>del l[2:5]
>>>print(l)
[0, 1, 5, 6, 7, 8, 9]

3.1.5 Updating Lists


A list is a mutable data type. This means we can update the elements of the list. Multiple
values can be added into list. We can use assignment(=) operator to change an item or a range
of items. We can update items of the list by simply assigning the value at the particular index
position.
Example:
>>> list1=[10, 20, 30, 40, 50]
>>> list1
[10, 20, 30, 40, 50]
>>> list1[0]=0 # change 0th element
>>> list1
[0, 20, 30, 40, 50]
>>> list1[1]=[5,10] # change 1st element as sublist
>>> list1
[0, [5,10], 30, 40, 50]
>>> list1[1:1]=[3,4] # add elements to a list at the desired
location
>>> list1
[0, 3, 4, [5, 10], 30, 40, 50]
There are flowing three list methods to update the list:
1. append()
2. extend()
3. insert()

M. V. Khasne Data Structures in Python


P a g e | 10

1. append():
The append() method adds an element to the end of a list. We can insert single item in
the list data item with append().
Example:
>>> list[10, 20, 30]
>>> list1.append(40)
>>> list1
[10, 20, 30, 40]

2. extend():
The extend() method extends a list by appending items. We can add several items
using extend() method.
Example:
>>> list1[10, 20, 30, 40]
>>> list1.extend([50, 60])
>>>list1
[10, 20, 30, 40, 50, 60]

3. insert(int, item):
This function is used to insert values, anywhere in the list. The first argument of the list
takes the index where the items will be inserted and second is the value that has to be
inserted.
Example:
>>> myList = ['Python', 'C++', 'Java', 'Ruby', 'Perl']
>>> myList.insert(1, 'JavaScript')
>>> print myList
['Python', 'JavaScript', 'C++', 'Java', 'Ruby', 'Perl']
>>> list1
[10, 20, 30]
>>> list1.insert(1,[15, 25])
[10,[15, 25], 20, 30]

3.1.6 Basic List Operations


3.1.6.1 Slicing Lists:
To print a specific range of elements of a List, we use Slice operation. The Slice operation is
performed on List with the use of colon (:). We have following varieties to perform Slicing
operation.
 To print elements from beginning to a range, use syntax [ : Index]
 To print elements from end, use syntax [:- Index]
 To print elements from specific Index till the end, use syntax [Index :]
 To print elements within a range, use syntax [Start_Index : End_Index]
 To print whole List with the use of slicing operation, use syntax [:]
 To print whole List in reverse order, use syntax [: :-1]

M. V. Khasne Data Structures in Python


P a g e | 11

Example:

List1=['P','Y','T','H','O','N','P','R','O','G', 'R','A', 'M','S']


print("Original List: ")
print(list1)
sliced_list1=listl[3:8]
print("Slicing elements in a range 3-8: ")
print(sliced_list1)
sliced_list2=list1[5:]
print("Printing sliced elements from 5th index till the end: ")
print(sliced_list2)
sliced_list3=list1[:]
print("Printing all elements: ")
print(sliced_list3)
sliced_list4=list1[:-5]
print("Printing sliced elements upto -5 index: ")
print(sliced_list4)
sliced_list5=listl[:5]
print("Printing sliced elements upto 5th index ")
print(sliced_list5)
sliced_list6=list1[::-1]
print("Printing list elements in reverse order")
print(sliced_list6)
sliced_list7=list1[0:14:2]
print("Printing list elements with step size 2")
print(sliced_list7)

Output:
Original List:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'G', 'R', 'A', 'M', 'S']
Slicing elements in a range 3-8:
['H', 'O', 'N', 'P', 'R']
Printing sliced elements from 5th index till the end:
['N', 'P', 'R', 'O', 'G', 'R', 'A', 'M', 'S']
Printing all elements:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'G', 'R', 'A', 'M', 'S']
Printing sliced elements upto -5 index:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O']
Printing sliced elements upto 5th index
['P', 'Y', 'T', 'H', 'O']
Printing list elements in reverse order
['S', 'M', 'A', 'R', 'G', 'O', 'R', 'P', 'N', 'O', 'H', 'T', 'Y', 'P']
Printing list elements with step size 2
['P', 'T', 'O', 'P', 'O', 'R', 'M']

M. V. Khasne Data Structures in Python


P a g e | 12

3.1.6.2 Repeating the List


Sometimes, there is a requirement to repeat all the elements of the list a specific number
of times. Python overloads the multiplication operator * to repeat the list n number of
times. For example, if we want to write all the elements of the list 5 times, we do not need
to write 5 print statements. We need to perform this task using the multiplication operator
with the list.
Example:

l=[int(x) for x in input("Enter the elements of list: ").split()]


n=int(input("How many times you want to repeat the list? "))
print(l*n)

Output:
Enter the elements of list: 2 3 4 5
How many times you want to repeat the list 4
[2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5]

3.1.6.3 Concatenation of the list


The concatenation operation is simply used to combine the elements of two lists. In the
Python programming language, the + plus operator is overloaded to perform the
concatenation of two lists. If we want to concatenate and merge two lists, we simply need to
write the plus operator between the two lists. After concatenation, the list on the right-hand
side of the plus operator is appended to the end of the list, which is on the left-hand side of
the + operator.

Example:

l1=[10,20,30]
l2=[40,50,60]
print("List after concatenation is:",l1+l2)

Output:
List after concatenation is: [10, 20, 30, 40, 50, 60]

3.1.6.4 Checking the membership of the element


Sometimes, there is a requirement to check whether the particular element is part of the list or
not. We can check the membership of the element of the list using the in or not in operator.
The in operator returns true if the element is found in the list and it returns false if the
element is not found in the list. The not in operator returns true if the element is not found in
the list and it returns false if the element is found in the list.

M. V. Khasne Data Structures in Python


P a g e | 13

Example:

l=[int(x) for x in input("Enter elements of the list:").split()]


x=int(input("Enter the element you want to check the membership"))
print("Result of in operator")
print("Element found in list? True or False:",x in l)
print("Result of not in operator")
print("Element not found in list? True or False?", x not in l)

Output:
Enter elements of the list:1 2 3 4 5
Enter the element you want to check the membership3
Result of in operator
Element found in list? True or False: True
Result of not in operator
Element not found in list? True or False? False

3.1.6.5 Iterating over the list


List is equivalent to arrays in other languages, with the extra benefit of being dynamic in size.
In Python, list is a type of container in Data Structures, which is used to store multiple data at
the same time. Unlike Sets, the lists in Python are ordered and have a definite count.
There are multiple ways to iterate over a list in Python.

Method #1: Using For loop

list = [1, 3, 5, 7, 9]
# getting length of list
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])

Output:
1
3
5
7
9

M. V. Khasne Data Structures in Python


P a g e | 14

Method #2: Using while loop


list = [1, 3, 5, 7, 9]
# Getting length of list
length = len(list)
i = 0
# Iterating using while loop
while i < length:
print(list[i],end=" ")
i += 1

Output:
1 3 5 7 9

Method #3: Using list comprehension

list = [1, 3, 5, 7, 9]
# Using list comprehension
[print(i,end=" ") for i in list]

Output:
1 3 5 7 9

3.1.7 Built-in List Functions


Sr.
Built-in Function Description Example
No.
>>> list1
[1, 2, 3, 4, 5]
1 len(list) It returns the length of the list.
>>> len(list1)
5
>>> list1
It returns the item that has the [1, 2, 3, 4, 5]
2 max(list)
maximum value in the list. >>> max(list1)
5
>>> list1
It returns the item that has the [1, 2, 3, 4, 5]
3 min(list)
minimum value in the list. >>> min(list1)
1
>>> list1
Calculates sum of all the elements of [1, 2, 3, 4, 5]
4 sum(list)
the list. >>> sum(list1)
15
>>> t1
(1, 2, 3, 4, 5)
5 list(seq) It converts a tuple into list.
>>> list(t1)
[1, 2, 3, 4, 5]

M. V. Khasne Data Structures in Python


P a g e | 15

3.1.8 Methods of list class


We have already discussed some methods of list class like:
 list.append()
 list.insert()
 list.extend()
 list.pop()
 list.remove()
 list.clear()

Remaining methods are:


Sr.
Methods Description Example
No.
>>> list1
It returns number of
[1, 2, 3, 4, 5, 3]
1 list.count(item) times the item occurs in
>>> list1.count(3)
the list.
2
It returns the index >>> list1
number of the item. If [1, 2, 3, 4, 5, 3]
2 list.index(item) item appears more than >>> list1.index(4)
one time, it returns the 3
lowest index number.
>>> list1
It reverses the position [1, 2, 3, 4, 5]
3 list.reverse()
of the item in the list. >>> list1.reverse()
[5, 4, 3, 2, 1]
>>> list1
Sorts the items in the
[1, 4, 3, 5, 2]
list.
>>> list1.sort()
4 list.sort() To sort elements in
[1, 2, 3, 4, 5]
reverse order use
>>>list1.sort(reverse=True)
reverse=True
[5, 4, 3, 2, 1]
>>> list1
This method is used to
[1, 2, 3, 4, 5]
create a copy of the
5 list.copy() >>> l2=list1.copy()
existing list’s elements.
>>> l2
[1, 2, 3, 4, 5]

M. V. Khasne Data Structures in Python


P a g e | 16

3.2 Tuples
A Python tuple is a sequence of data values called items or elements. A tuple is a linear data
structure which means that the elements are stored in a linear order one after another. A tuple
is an immutable data type which means a tuple once created cannot be altered. In other
words, a tuple works in a similar fashion as a list but the tuples cannot be updated while lists
can be updated. This restricts the number of operations that can be performed on the tuples.
The tuple data structure is used only when we do not want to update the values of the tuple. If
we want to update the values of the tuple, the only method to do so is to create a new tuple
object as if we try to update the existing tuple, it will raise an error. Likewise a list, a tuple is
a collection of logically related variables of different data types. This means a list is a
collection of heterogeneous data items that one can store values of different types in it.
In Python, a tuple is used to handle a large amount of heterogeneous data, without the need to
declare many individual variables of different types. The elements of the tuples are stored in
the contiguous memory locations, i.e., one after another. Tuple elements can be of any
primitive data types or any sequence data types or a combination of both. A Python tuple can
have any number of elements or items. The main restriction on a tuple is that we cannot
change the value of the existing tuple.

3.2.1 Advantages of a tuple:


A tuple is a data structure used in Python that provides almost all functionalities provided by
the array data structure. This section describes the advantages of a tuple in Python:
 Immutable: Tuples are immutable data types used in Python. By the term immutability,
we mean that we cannot make changes in the existing tuple object. It offers the security to the
data. If somebody tries to change the values of the tuple, this operation raises an error. This
can be useful when tuples are to be transported between different applications.
 Functionality: The tuple data type comes with several functions that allow the user to
easily perform different set of operations instead of writing long code from scratch. You can
use dir(tuple) to get a list of all functions provided by a tuple.
 Heterogeneous: One of the biggest advantages of using a tuple is that we can create a
tuple of heterogeneous elements. We can store the elements of different data types in a single
tuple. The elements of different types consume memory according to the value of a particular
type stored in the tuple.
 Multidimensional: We can use the tuple as a multidimensional data structure. With the
help of a multidimensional tuple, we can easily create a matrix and we can also perform
different matrix operations on the tuple.
 Easy to display values: It is very easy to display different values stored in the tuple. We
can even display the values of the tuple without iterating over the tuple. To print the tuple in a
simple manner, we simply need to write the print statement and pass the tuple of that object
to the print function which we want to display.
 Performance: A tuple is immutable in nature and has a fixed size in memory. We can
easily allocate memory space to the tuple at the time of creation and storage requirement is
fixed. We do not need to look for the memory space again and again as the requirement of the
user changes at run time.

M. V. Khasne Data Structures in Python


P a g e | 17

 Speed: Since tuples are immutable, iterating through tuples is faster than with lists. So,
there is a slight performance boost.

Advantages of Tuples in Python over Lists:


The main difference between Python tuples and lists is that the elements of a tuple cannot be
changed once they are assigned; whereas, the elements of a list can be changed.
As tuples and lists are quite similar to each other, they are often used in similar kinds of
situations. Although, a tuple in Python has a bunch of advantages over lists. Following are
some of the main advantages:
 Iteration in a tuple is faster as compared to lists since tuples in Python are immutable.
 Tuples are generally used for different Python Data Types; whereas, lists are used for
similar data types.
 Whenever, we need to make sure that the data remains unchanged and write protected,
Python tuple is the best option.

3.2.2 Difference between List and Tuple


Sr.
LIST TUPLE
No.

1 Lists are mutable. Tuples are immutable.

Implication of iterations is Time- Implication of iterations is comparatively


2
consuming. Faster.

The list is better for performing


Tuple data type is appropriate for
3 operations, such as insertion and
accessing the elements.
deletion.

Tuple consume less memory as compared


4 Lists consume more memory.
to the list

Tuple does not have much built-in


5 Lists have several built-in methods.
methods.

The unexpected changes and errors


6 In tuple, it is hard to take place.
are more likely to occur.

M. V. Khasne Data Structures in Python


P a g e | 18

3.2.3 Creating Tuples


In Python, a tuple is written as a sequence of data values separated by commas (,). The tuple
can be created using round brackets ( ). Every value has a location index range from 0 to n-1
(where n is the total number of the elements in the tuple).
3.2.3.1 Creation of a tuple by assigning values
The different methods to define the tuple by assignment operators are as follows:
 t=() #it creates an empty tuple with name t
 t_I=(20,30,40,50) # it creates the tuple of integers with name t_I
 t_S=("Hello", "World", "This", "is", "Python") #it creates a tuple of
strings with name t_s
 t_H=(20, "Hello", 30.4) #it creates a tuple of heterogeneous data items with name
t_H
 tup2 = 1,2,3,4 # tuple can be created without parenthesis

a. Python Tuples Packing


You can also create a Python tuple without parentheses. But it is best practice to use
parentheses. When we create any tuple it is called tuple packing.

>>> b= 1, 2.0, 'three'

b. Python Tuples Unpacking


Python tuple unpacking is when you assign values from a tuple to a sequence of variables
in python. This process is also known as tuple assignment. It allows assignment of values to
a tuple of variables on the left side of assignment from the tuple of values on the right side of
the assignment.

>>> percentages=(99,95,90,89,93,96)
>>> a,b,c,d,e,f=percentages
>>> c
90
>>> languages=('Python', 'Java')
>>> (a,b)=languages
>>> a
Python

Swapping of two variables can be solved by using tuple assignment.


>>> x=10
>>> y=20
>>> print(x,y)
10 20
>>> x,y=y,x
>>> print(x,y)
20 10

M. V. Khasne Data Structures in Python


P a g e | 19

c. Creating a tuple with a single item


Until now, we have seen how easy it is to declare a Python tuple. But when you do so with
just one element, it may create some problems. Let’s take a look at it.
>>> a=(1)
>>> type(a)
<class ‘int’>

Wasn’t the type() method supposed to return class ‘tuple’?


To get around this, we add a comma after the item.
>>> a=(1,)
>>> type(a)
<class ‘tuple’>

Problem solved. And as we saw in tuple packing, we can skip the parentheses here.
>>> a=1,
>>> type(a)
<class ‘tuple’>

3.2.4 Accessing values in Tuples


Accessing elements from the tuple is a method to get values stored in the tuple from a
particular location or index. There are mainly three methods to get values from the list.

3.2.4.1 Indexing of Tuples in Python


To access an element of a tuple, we simply use the index of that element. We use square
brackets around that index number as shown in the example below:

>>> tup1 = (1, 2, 3)


>>> print (tup1[0])
1

3.2.4.2 Reverse Indexing of Tuples in Python


Much similar to regular indexing, here, we use the index inside the square brackets to access
the elements, with only one difference, that is, we use the index in a reverse manner.
Meaning, the indexing of the elements would start from the last element. Here, we use
indexes as −1, −2, −3, and so on, where −1 represents the last element.
Following code block is an example to access elements using reverse indexing.
>>> tup1 = (1, 2, 3)
>>> print (tup1[-1])
3

M. V. Khasne Data Structures in Python


P a g e | 20

3.2.4.3 Slicing Operator of Tuples in Python


Using the slicing operator to access elements is nothing new, as we have seen this in previous
modules as well. As the name suggests, we will slice, that is, extract some elements from the
tuple and display them. To do this, we use a colon between the index from where we want to
start slicing and the index till where we want to perform it.
Following code block is an example to show how to access elements using the slicing
operator.

>>> tup3 = (1,2,3,4,5,6)


>>> tup3[1:]
>>>tup3[2:4]
(2, 3, 4, 5, 6)
(3, 4)

 Accessing all the elements from a particular tuple at once allows the user to access all
the values from the tuple only by writing tuple name in print() statement.
>>> print(tup3)
(1,2,3,4,5,6)

3.2.5 Deleting Values in Tuples


Since a tuple in Python is an immutable data type in Python, deleting particular elements in a
tuple is not possible. But, the whole tuple can be deleted using the del keyword as shown in
the following example:
>>> tup1 = (10, 20, 30)
>>> print (tup1)
>>> del tup1
>>> print (tup1)
(10, 20, 30)

Traceback (most recent call last):


File “”, line 1, in
NameError: name ‘tup1’ is not defined

 If we want to remove specific elements from a tuple then Python does not provide any
explicit statement but we can use index slicing to leave out a particular index.
>>> t1=(10, 20, 30, 40, 50)
>>> t2=t1[:2] + t1[3:]
>>> print(t2)
(10, 20, 40, 50)

 We can convert tuple into a list, then remove the item and convert back to a tuple.
>>> t1=(10, 20, 30, 40, 50)
>>> l1=list(t1)
>>> del l1[2]
>>> t2=tuple(l1)
>>> print(t2)
(10, 20, 40, 50)

M. V. Khasne Data Structures in Python


P a g e | 21

3.2.6 Updating Tuples


Again, since tuple is immutable, it is impossible to change or modify the value of a particular
element. Although, we can take some portion of an existing tuple and create a new tuple
using the concatenating operator, as shown in the example below:

>>> t1 = ('a', 'b', 'c')


>>> t2 = (1, 2, 3)
>>> t1[1] = 'd'
Traceback (most recent call last):
File “”, line 1, in
t1[1] = ‘d’
TypeError: ‘tuple’ object does not support item assignment
>>> t3 = t1 + t2
>>> print(t3)
(‘a’, ‘b’, ‘c’, 1, 2, 3)

 If the element of tuple is itself a mutable data type like list, its nested items can be
changed as shown:
>>> t1 = (10, 20, 30, [40, 50])
>>> t1[3][0] = 11
>>> t1[3][1] = 12
>>> print(t1)
(10, 20, 30, [11, 12])

 We can convert tuple into a list, then update the item and convert back to a tuple.
>>> t1 = (10, 20, 30, 40, 50)
>>> l1 = list(t1)
>>> l1[2] = 60
>>> t2 = tuple(l1)
>>> print(t2)
(10, 20, 60, 40, 50)

3.2.7 Basic Tuple Operations


We can apply a set of operations to the tuple. This section enlists some of the operations of
the tuple.

3.2.7.1 Slicing the Tuple


Python provides the most powerful feature of slicing. Slicing is an operation that can be
performed on the sequence to get part of the sequence. When slicing is applied to the tuple,
we can extract the part of the tuple from the start to the end, which is mentioned in the square
brackets. The syntax is tuple[start:end:stepsize].
The following program explains the concept of slicing on a tuple:

t=(1,2,3,4,5,6,7,8)
print("Value from index 1 to 4:",t[1:5])
print("Value from index 1 to end:",t[1:])
print("Value from starting to 4:",t[:5])
print("Value from alternate index from starting till end:",t[::2])
print("Value from alternate index starting from 2 till 6:",t[2:7:2])

M. V. Khasne Data Structures in Python


P a g e | 22

Output:
Value from index 1 to 4: (2, 3, 4, 5)
Value from index 1 to end: (2, 3, 4, 5, 6, 7, 8)
Value from starting to 4: (1, 2, 3, 4, 5)
Value from alternate index from starting till end: (1, 3, 5, 7)
Value from alternate index starting from 2 till 6: (3, 5, 7)

3.2.7.2 Repeating the Tuple


Sometimes, there is a requirement to repeat all the elements of the tuple a specific number of
times. Python overloads the multiplication operator * to repeat the tuple n number of times.
For example, if we want to write all the elements of a tuple five times, we do not need to
write five print statements; we just need to perform this task using the multiplication operator
with the tuple.
Example:

t=tuple(int(x) for x in input("Enter elements of tuple:").split())


x=int(input("How many times you want to repeat elements of the tuple:"))
print("Elements after repeating are:",t*x)

Output:
Enter elements of tuple:2 3 4 5
How many times you want to repeat the elements of the tuple:3
Elements after repeating are: (2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5)

3.2.7.3 Concatenation of a tuple


The concatenation operation is simply used to combine the elements of two tuples. In the
Python programming language, the + plus operator is overloaded to perform the
concatenation of two tuples. If we want to concatenate and merge two tuples, we simply need
to write the plus operator between the two tuples. After concatenation, the tuple on the right-
hand side of the plus operator is concatenated with the tuple on the left-hand side of the +
operator. The following program shows the concatenation operation of the two tuples:
Example:

t1=(10,20)
t2=(39,40)
print("Tuples after concatenation operation is: ",t1+t2)

Output:

Tuples after concatenation operation is: (10, 20, 39, 40)

M. V. Khasne Data Structures in Python


P a g e | 23

3.2.7.4 Checking the membership of the element


Sometimes, there is a requirement to check whether a particular element is part of the tuple of
not. We can check the membership of the element of the tuple using the in or not in operator.
The in operator returns true if the element is found in the tuple and it returns false if the
element is not found in the tuple. The not in operator returns true if the element is not found
in the tuple and it returns false if the element is found in the tuple. This is shown by the
following examples:

t=(1,5,46,3,9)
print("Result of in operator")
print("Element 3 found in tuple true or false?",3 in t)
print("Result of not in operator")
print("Element 3 not found in tuple true or false?",3 not in t)

Output:
Result of in operator
Element 3 found in tuple true or false? True
Result of not in operator
Element 3 not found in tuple true or false? False

3.2.7.5 Updating Tuple using Concatenation Operator

t=(1,5,46,3,9)
print("Tuple before updating is: ",t)
t1=()
t1=t[:1]+(8,)+t[1:]
print("Tuple after updating at index 1 is: ",t1)

Output:
Tuple before updating is: (1, 5, 46, 3, 9)
Tuple after updating at index 1 is: (1, 8, 5, 46, 3, 9)

3.2.7.6 Iterating over a tuple


Iterating over a tuple specifies the way in which the loop can be applied to the tuple. There is
a need to iterate over the tuple if we want to extract the individual elements from the tuple.
We can iterate over the tuple using for or while iterative statements.
 The for loop
The for loop is an iterative control statement that iterates for each element of the tuple
from starting index till end index.
t=(1,2,3,4,5)
for i in t:
print(i,end=" ")

Output:
1 2 3 4 5

M. V. Khasne Data Structures in Python


P a g e | 24

3.2.8 Built-in Tuple Functions


Sr.
Built-in Function Description Example
No.
>>> t1
It returns the length of the (1, 2, 3, 4, 5)
1 len(tuple)
tuple. >>> len(t1)
5
>>> t1
It returns the item that has
(1, 2, 3, 4, 5)
2 max(tuple) the maximum value in the
>>> max(t1)
tuple.
5
>>> t1
It returns the item that has
(1, 2, 3, 4, 5)
3 min(tuple) the minimum value in the
>>> min(t1)
tuple.
1
It zips elements from two >>> t1=(1,2)
tuples into a list of tuples. >>> t2=('a', 'b')
The purpose of zip() is >>> t3=zip(t1,t2)
4 zip(tuple1,tuple2) to map the similar index >>> t3=list(t3)
of multiple containers so >>> print(t3)
that they can be used just [(1, 'a'), (2, 'b')]
using as single entity.
>>> l1
[1, 2, 3, 4, 5]
5 tuple(seq) It converts a list into tuple.
>>> tuple(l1)
(1, 2, 3, 4, 5)
>>> t1=(3,2,4,1)
This function is used to
>>> sorted(t1)
sort the tuples elements in
6 sorted(list) (1,2,3,4)
ascending or descending
>>> sorted(t1,teverse=true)
order.
(4,3,2,1)

Methods of Tuple:
Sr.
Method Description Example
No.
>>> t1
Returns the number of
(1, 2, 3, 2, 5)
1 count() times a specified value
>>> t1.count(2)
occurs in a tuple.
2
Searches the tuple for a >>> t1
specified value and (1, 2, 3, 4, 5)
2 index()
returns the position where >>> t1.index(4)
it was found 3

M. V. Khasne Data Structures in Python


P a g e | 25

3.3 Sets
A Set in Python is mutable, iterable, and does not have any duplicate elements. It is an
unordered collection of elements which means that a set is a collection that stores elements
of different Python Data Types. Remember that a set in Python doesn’t index the elements in
a particular order. Let us look at some of the properties of sets in Python. Sets in Python are
usually used to perform some mathematical functions such as union, intersection, difference
and complement etc.
 In Python sets, elements don’t have a specific order.
 Sets in Python can’t have duplicates. Each item is unique.
 The elements of a set in Python are immutable. They can’t accept changes once added.
 But, don’t get confused with the fact that sets in Python are mutable. Python sets allow
addition and deletion operations.

3.3.1 Defining and Accessing values in Sets


To declare a set, you need to type a sequence of items separated by commas, inside curly
braces. After that, assign it to a Python variable.
>>> a={1,3,2}
A set may contain values of different types.
>>> c={1,2.0,'three'}
>>> print(c)
{1,2.0,'three'}
>>> print(type(c))
<class 'set'>

A set doesn't store duplicate objects. Even if an object is added more than once inside the
curly brackets, only one copy is held in the set object. Hence, indexing and slicing operations
cannot be done on a set object.

>>> S1={1, 2, 2, 3, 4, 4, 5, 5}
>>> S1
{1, 2, 3, 4, 5}

set() function
Python has an in-built function set() using which a set object can be constructed out of any
sequence such as a string, list or a tuple object.
>>> s1=set("Python")
>>> s1
{'t', 'h', 'o', 'n', 'P', 'y'}
>>> s2=set([45,67,87,36, 55])
>>> s2
{67, 36, 45, 87, 55}
>>> s3=set((10,25,15))
>>> s3

M. V. Khasne Data Structures in Python


P a g e | 26

{25, 10, 15}


>>> s4=set(range(1,3))
{1,2}

The order of elements in the set is not necessarily the same as the order given at the time of
assignment. Python optimizes the structure of a set for performing operations over it, as
defined in mathematics.
Only immutable (and hashable) objects can be a part of a set object. Numbers (integer, float,
as well as complex), strings, and tuple objects are accepted, but list and dictionary objects are
not.
>>> S1={(10,10), 10,20}
>>> S1
{10, 20, (10, 10)}
>>> S2={[10,10], 10,20}
TypeError: unhashable type: 'list'

In the above example, (10,10) is a tuple, hence it becomes part of the set. However, [10,10] is
a list, hence an error message is displayed saying that the list is unhashable. (Hashing is a
mechanism in computer science which enables quicker search of objects in the computer's
memory.)
Note: Even though mutable objects are not stored in a set, the set itself is a mutable object.

 Iterating over Python Set

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday',
'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

M. V. Khasne Data Structures in Python


P a g e | 27

3.3.2 Deleting values in Set


Again, because a set isn’t indexed, you can’t delete an element using its index. So for this,
you must use one the following methods. A method must be called on a set, and it may alter
the set. For the following examples, let’s take a set called numbers.
>>> numbers={3,2,1,4,6,5}
>>> numbers
{1, 2, 3, 4, 5, 6}

1. discard() :
This method takes the item to delete as an argument.
>>> numbers.discard(3)
>>> numbers
{1, 2, 4, 5, 6}
As you can see in the resulting set, the item 3 has been removed.

2. remove() :
Like the discard() method, remove() deletes an item from the set.
>>> numbers.remove(5)
>>> numbers
{1, 2, 4, 6}

 discard() vs remove()-
These two methods may appear the same to you, but there’s actually a difference. If you
try deleting an item that doesn’t exist in the set, discard() ignores it, but remove()
raises a KeyError.
>>> numbers.discard(7)
>>> numbers
{1, 2, 4, 6}
>>> numbers.remove(7)
Traceback (most recent call last):
File “<pyshell#37>”, line 1, in <module>
numbers.remove(7)
KeyError: 7

3. pop() :
Like on a dictionary, you can call the pop() method on a set. However, here, it does not
take an argument. Because a set doesn’t support indexing, there is absolutely no way to
pass an index to the pop method. Hence, it pops out an arbitrary item. Furthermore, it
prints out the item that was popped.

>>> numbers.pop()
1

M. V. Khasne Data Structures in Python


P a g e | 28

Let’s try popping another element.


>>> numbers.pop()
2

4. clear() :
Like the pop() method, the clear() method for a dictionary can be applied to a Python
set as well. It empties the set in Python.
>>> numbers.clear()
>>> numbers
set()

As you can see, it denoted an empty set as set(), not as {}.

3.3.3 Updating Sets


As we discussed, a Python set is mutable. But as we have seen earlier, we can’t use indices to
reassign it. So, we use two methods for this purpose- add() and update().

1. Add() :
It takes as argument the item to be added to the set.
>>> numbers={3,1,2,4,6,5}
>>> numbers.add(3.5)
>>> numbers
{1, 2, 3, 4, 5, 6, 3.5}

If you add an existing item in the set, the set remains unaffected.
>>> numbers.add(4)
>>> numbers
{1, 2, 3, 4, 5, 6, 3.5}

2. update() :
This method can add multiple items to the set at once, which it takes as arguments.
>>> numbers.update([7,8],{1,2,9})
>>> numbers
{1, 2, 3, 4, 5, 6, 3.5, 7, 8, 9}

As is visible, we could provide a list, set, strings, and tuples as arguments to this. This is
because this is different than creating a set.

3.3.4 Basic Set Operations


As mentioned earlier, the set data type in Python implements as the set defined in
mathematics. Various set operations can be performed. Operators |, &, - and ^ perform union,
intersection, difference and symmetric difference operations, respectively. Each of these

M. V. Khasne Data Structures in Python


P a g e | 29

operators has a corresponding method associated with the built-in set class like union(),
intersection(), difference(), symmetric_difference().

1. Union:
This method performs the union operation on two or more Python sets. What it does is it
returns all the items that are in any of those sets.

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1|s2
{1, 2, 3, 4, 5, 6, 7, 8}
>>> s2.union(s1)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set1.union(set2,set3)
{1, 2, 3, 4, 5, 6, 7}

2. Intersection:
This method takes as argument sets, and returns the common items in all the sets.

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1&s2
{4, 5}
>>> s1.intersection(s2)
{4, 5}
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set2.intersection(set1,set3)
set()
It returned an empty set because these three sets have nothing in common.

M. V. Khasne Data Structures in Python


P a g e | 30

3. Difference:
The difference operation returns the difference of two or more sets. It returns as a set.

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1-s2
{1, 2, 3}
>>> s2-s1
{8, 6, 7}
>>> s1.difference(s2)
{1, 2, 3}
>>> s2.difference(s1)
{8, 6, 7}
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set1.difference(set2,set3)
{1, 2}

4. Symmetric Difference:
The result of symmetric difference is a set consisting of elements in both sets, excluding
the common elements.

>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1^s2
{1, 2, 3, 6, 7, 8}
>>> s2^s1
{1, 2, 3, 6, 7, 8}

M. V. Khasne Data Structures in Python


P a g e | 31

>>> s1.symmetric_difference(s2)
{1, 2, 3, 6, 7, 8}
>>> s2.symmetric_difference(s1)
{1, 2, 3, 6, 7, 8}

 Membership
We can apply the ‘in’ and ‘not in’ python operators on items for a set. This tells us
whether they belong to the set.
>>> 'p' in {'a','p','p','l','e'}
True

>>> 0 not in {'0','1'}


True

3.3.5 Deleting a set


The del keyword will delete the set completely.

>>> myset = {"apple", "banana", "cherry"}


>>> del myset
>>> myset
Traceback (most recent call last):
File "", line 1, in
NameError: name ‘myset’ is not defined

3.3.6 Built-in Set Functions


Consider set a = {6, 1, 3, 2}
Sr. Built-in
Description Example
No. Function
Returns True if all elements of the set >>> all(a)
1 all()
are true (or if the set is empty) True
Returns True if any element of the set is >>> any(a)
2 any()
true. If the set is empty, returns False. True
Returns the length (number of items) of >>> len(a)
3 len()
the set. 4
Returns the maximum element in the >>> max(a)
4 max()
set. 6
Returns the minimum element in the >>> min(a)
5 min()
set. 1
Returns a new sorted list from the >>> sorted(a)
6 sorted() elements in the set (does not sort the set [1, 2, 3, 6]
itself).
Returns the sum of all elements in the >>> sum(a)
7 sum()
set. (Not applicable to strings) 12

M. V. Khasne Data Structures in Python


P a g e | 32

Methods of Sets:
We have already discussed the methods on set like union(), intersection(),
difference(), symmetric_difference(), add(), discard(), remove(),
pop(), update(). Remaining methods on set are:
Sr.
Method Description Example
No.
>>> set1={1,2,3}
As we discussed in >>> set2={3,4,5}
intersection(), it does not >>>
1 intersection_update() update the set on which it is set1.intersection_updat
called. For this, we have the e(set2)
intersection_update() method. >>> set1
{3}
>>> set1={1,2,3}
>>> set2={3,4,5}
Like intersection-update(),
>>>
this method updates the
2 difference_update() set1.difference_update(
Python set with the
set2)
difference.
>>> set1
{1,2}
>>> set1={1,2,3}
Like the two methods we >>> set2={3,4,5}
discussed before this, it >>>
symmetric_difference_
3 updates the set on which it is set1.symmetric_differen
update()
called with the symmetric ce_update(set2)
difference. >>> set1
{1, 2, 4, 5}
>>> max(a)
The copy() method creates a 6>>> set4=set1.copy()
4 copy() shallow copy of the Python >>> set1,set4
set. ({1, 2, 4, 5}, {1, 2,
4, 5})
>>>
This method returns True if
{1,3,2}.isdisjoint({4,5
5 isdisjoint() two sets have a null
,6})
intersection.
True
This method returns true if >>>
6 issubset() the set in the argument {1,2}.issubset({1,2,3})
contains this set. True
Like the issubset() method, >>>
this one returns True if the set {1,3,4}.issuperset({1,2
7 issuperset()
contains the set in the })
argument. False

M. V. Khasne Data Structures in Python


P a g e | 33

3.4 Dictionaries
The Python Dictionary is a sequence of data values called items or elements. A dictionary is
an associative data structure, which means that elements are stored in a non-linear fashion.
In Python, a list or tuple is referred to as a linear data structure in which the elements are
stored one after other, i.e., the first element, then the second element, then the third, and so
on. The linear data structure is required when the elements need to be accessed in a sequential
order or one after another or when someone simply needs to access the elements directly by
indexes. In the associative data structure, the elements are not stored in the sequence entered
by the user, so each element is associated with a key. The elements are accessed using keys.
The dictionary data structure represents a group of elements arranged in the form of key-
value pairs. The values of the dictionary are accessed by keys easily, so we do not need to
bother about the order in which the elements are stored. The dictionary data type is a flexible
data type that can be modified according to the requirement, which makes it a mutable data
type. This means we can update the already existing dictionary and there is no need to create
a new dictionary object. The Python dictionary is similar to that of a list. The main difference
is that a dictionary contains the elements in key-value pairs. The dictionary is a collection of
heterogeneous data items. One can store values of different types in it. The values in the
dictionary are mutable in nature and the keys are immutable in nature. We can modify the
value associated with the key, but there is no way to change the keys of a particular value. A
tuple can easily become the keys for the dictionary while a list can easily become the values
of the dictionary. Moreover, a dictionary can dynamically expand or shrink when elements
are added to or removed from it. In Python, the dictionary is used to handle a large amount of
heterogeneous data, without the need to declare many individual variables of different types.
The elements of the dictionary are not stored in the order entered by the user. Dictionary keys
and values can be of various types such as integer, float, or string types. The Python
dictionary can have any number of elements or items. The keys in the dictionary do not
contain the same value for different elements whereas values in the dictionary may contain
the same values for different elements. If we try to insert the value with the same key, the
newly inserted values replace the old value associated with that key. The following table
shows the representation of a dictionary:
Keys Values
Marks 69.5
Roll No. 54
Name Nilesh
Phone 9898989898
5 691.4

Each dictionary value is accessed and manipulated using a dictionary name followed by a
unique key in square brackets associated with the particular value. In the preceding table,
Marks key is associated with value 69.5, Roll No. key is associated with value 54, Name key
is associated with the value Nilesh, Phone key is associated with the value 9898989898, and
the key 5 is associated with the value 691.44.

M. V. Khasne Data Structures in Python


P a g e | 34

3.4.1 Advantages of the dictionary:


The dictionary is a data structure used in Python that provides almost all functionalities
provided by the list. This section describes the advantages of the dictionary in Python.
1. Mutable: Dictionaries are mutable data types used in Python. By the term mutability, we
mean that we can create changes in the existing dictionary object; we do not need to
create a new object every time we need to update the existing dictionary.
2. Flexibility: The dictionary offers the flexibility or scalability to the user. We can easily
insert or delete dictionary elements at run time and the dictionary expands and shrinks in
memory according to the requirement. Moreover, we do not need to declare the
dictionary before using it. The dictionary is declared automatically when we assign
values in {} (curly braces).
3. Functionality: The dictionary data type comes with several functions that allow the user
to easily perform different set of operations instead of writing long code from scratch.
You can use dir(dict) to get a list of all functions or attributes provided by the
dictionary.
4. Heterogeneous: One of the biggest advantages of using the dictionary is that we can
create the dictionary of heterogeneous elements. We can store the elements of different
data types in a single dictionary. The elements of different types consume memory
according to the value of the particular type stored in the list.
5. Dynamic: The dictionary data type is dynamic in nature. This means that for using the
dictionary, we do not need to declare the size of the dictionary. The dictionary consumes
memory according to the requirement. The dictionary automatically expands when the
user inputs data at run time and it also shrinks automatically when the user deletes data at
run time.
6. Easy to insert values: It is very easy to insert values in the dictionary. The dictionary
provides different methods to insert values in the dictionary. We can directly take the
input from the user in the form of key-value pairs or by taking the input first in the form
of a tuple or list and then assign a tuple as a key to the dictionary and assign a list as the
values of the dictionary.
7. Easy to display values: It is even very easy to display different values stored in the
dictionary. We can even display the values of the dictionary by without even iterating
over the dictionary. To print the dictionary in a simple manner, we simply need to write
the print statement and pass the dictionary object to the print function which we want to
display.
8. Availability of different methods: The dictionary also offers different set of inbuilt
methods. Using them, we can easily perform different set of tasks by simply calling these
methods with the dictionary object. For example, to sort the elements of the dictionary,
we do not need to write the complete code of sorting. We just need to call the sort
method of the list using the dictionary object we want to sort.
9. Easier to use: The dictionary data type is easier to use as compared with other data
types. It has the ability to take the memory dynamically and offers different functions to
provide an easy way to write code.

M. V. Khasne Data Structures in Python


P a g e | 35

10. Associative data structure: The dictionary data type is associative in nature. If we want
to get any value stored in the dictionary, we need to refer to the key associated with the
value. This is used when the location of the values stored in the sequence is not required
to access in a linear fashion.

3.4.2 Creating a Dictionary


Creating a dictionary In Python, a dictionary is written as a pair of elements in the form of
key-value pairs separated by commas (,). The keys and values are also separated by a colon
(:) where the value on the left-hand side of the colon represents the key and the value on the
right-hand side of the colon represents the value associated with the key. The dictionary can
be created using curly braces ({}). Every value has a location index ranging from 0 to n-1
(where n is the total number of the elements in the list). The syntax of defining the dictionary
is as follows:
<dictionary_name>={key1:value1,key2:value2,……………keyn:value }
The dictionary cannot be accessed or modified by the index; we can access and modify
the values with only keys.

3.4.2.1 Creation of the dictionary by assigning values


The simplest method to create a dictionary is to simply assign the pair of key-values to the
dictionary using the assignment operator. It is the simplest way to create a dictionary, but it is
not used for real-time inputs as the input is provided in the program by the programmer
statically. The different methods to define the dictionary by assignment operators are as
follows:
>>>D={ } #it creates an empty dictionary with name D
>>> D
{}
>>> d= {1: "Apple", 2: "Banana", 3: "Mangoes"} #it creates the dictionary d,
where keys 1,2,3 are associated with 3 fruits “Apple”, “Banana”, “Mangoes”. In this
representation keys are integer and values are strings.
>>> d={"Name": "Nilesh", "Gender": "M", "Ph":9898989898} # it creates a
dictionary where keys are strings and values are of different types.
>>> Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} # with Mixed keys

dict() Function:
Python provides built-in function dict() for creating a dictionary.
>>> d1=dict({1: "Orange", 2: "Mango", 3: "Banana"})
>>> d2=dict([(1, "Red"),(2, "Green"),(3, "Yellow")])
>>> d3=dict(one=1, two=2, three=3)
>>> d2
{1: 'Red',2: 'Green',3: 'Yellow'}
>>> d3
{'one':1, 'two':2, 'three':3}

M. V. Khasne Data Structures in Python


P a g e | 36

3.4.2.2 Create Dictionary by assigning values to the keys entered by a user


We can insert values in the dictionary by simply inputting keys from the user and assigning
values to that key. We can insert a single element in the dictionary at run time with this
method. If we want to insert multiple elements in the dictionary using the insert function, we
need to write the looping statement. The following program demonstrates the input procedure
in the dictionary:

n=int(input("Enter the number of elements:"))


d={}
print("Enter elements:")
for i in range(n):
k=input("Enter key:")
d[k]=input("Enter value:")
print(d)

Output:
Enter the number of elements:3
Enter elements:
Enter key: 1
Enter value: Orange
Enter key: 2
Enter value: Mango
Enter key: 3
Enter value: Banana
{'1': 'Orange', '2': 'Mango', '3': 'Banana'}

3.4.2.3 Create Dictionary using split() method:


The split() method in Python breaks up a string at the specified separator and returns the
list of string. Here, the separator is the space inserted while entering values from the
keyboard. The split() method creates a dictionary of elements in which the element
entered before pressing the space bar is considered a key and the element inserted after
pressing the space bar is considered a value associated with that key. If we want to input a
number of pairs using the split() method, we need to implement this method inside the
body of the loop. The split() method does not take any parameter. It takes a string from the
user and breaks that string by a separator, that is, space. The following program demonstrates
the procedure to input the dictionary elements using the split() method:

n=int(input("Enter the number of elements:"))


d=dict(input("Enter elements:").split() for i in range(n))
print("The created dictionary is:",d)

M. V. Khasne Data Structures in Python


P a g e | 37

Output:
Enter the number of elements: 3
Enter elements: Name Nilesh
Enter elements: Roll_no 54
Enter elements: Phone 9898989898
The created dictionary is: {'Name': 'Nilesh', 'Roll_no': '54', 'Phon
e': '9898989898'}

The preceding program takes elements in the form of a string from the user. It breaks the
inputted string into key-value pairs by a space separator. It inserts those broken strings as
elements in the dictionary.

3.4.2.4 Input dictionary via lists and tuples:


There is another method to input keys and values in the dictionary; in this method, we put the
keys in the form of tuples and values in the form of a list. After this, we just need to zip the
inputted tuple and list by the zip function and then convert the result to the dictionary.
Although, we can also take tuples as keys and values both and lists as keys and values both,
but it is recommended that you take tuples as keys and lists as values as tuple’s values are
immutable like keys in the dictionary and list values are mutable like values in the dictionary.
The following program demonstrates the procedure to create the dictionary using the
discussed method:

n=int(input("Enter the number of elements:"))


l=[]
l1=[]
for i in range(n):
k=input("Enter Key:")
v=input("Enter Value:")
l.append(k)
l1.append(v)
t=tuple(l)
d=dict(zip(t,l1))
print("The created dictionary is:",d)

Output:
Enter the number of elements:2
Enter Key: Name
Enter Value: Vijay
Enter Key: Age
Enter Value: 30
The created dictionary is: {'Name': 'Vijay', 'Age': '30'}

M. V. Khasne Data Structures in Python


P a g e | 38

3.4.2.5 Python Dictionary Comprehension:


You can also create a Python dict using comprehension. To do this, follow an expression pair
with a for-statement loop in python. Finally, put it all in curly braces.
>>> mydict={x*x:x for x in range(8)}
>>> mydict
{0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}

3.4.3 Accessing Values in a Dictionary


As discussed above, to access elements in a dictionary, we have to use keys instead of
indexes. Now, there are two different ways of using keys to access elements as shown below:

1. Using the key inside square brackets like we used to use the index inside square
brackets.
>>> d1={'Name': 'Nilesh', 'Roll_no': '54', 'Phone': '9898989898'}
>>> d1['Name']
'Nilesh'

2. Using the get() method and passing the key as a parameter inside this method.
>>> d1.get('Roll_no')
54
>>> d1.get('Name')
'Nilesh'

3.4.4 Deleting Values in Dictionary


 Delete elements using the pop() method:
We use the pop() Python Function to remove a particular element from a dictionary by
providing the key of the element as a parameter to the method as shown in the example
below:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


print(cubes.pop(4))
print(cubes)

Output:
64
{1: 1, 2: 8, 3: 21, 5: 125}

 Delete Elements Using the popitem() Method:


We can use the popitem() method to remove any randomly picked element as shown
in the example below.

M. V. Khasne Data Structures in Python


P a g e | 39

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


print(cubes.popitem())
print(cubes)

Output:
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}

 Delete Items Using the del Keyword in a Dictionary:


We use the del keyword to delete an item as shown in the following example:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


del cubes[5]
print (cubes)

Output:
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}

 Delete All Elements Using the Clear() Method:


We can use the clear() method, and it will clear out or delete all elements from a
dictionary at once as shown in the following example:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


cubes.clear()
print(cubes)

Output:
{}

 Deleting the Whole Dictionary:


As we have already seen, we can use the del keyword to delete a particular item by
passing the key of that particular item. We can also delete a whole dictionary at once
using the del() function as shown in the example below:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


cubes.del()
print(cubes)

Output:
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘cubes’ is not defined

M. V. Khasne Data Structures in Python


P a g e | 40

3.4.5 Updating Dictionary


The Dictionary is a mutable data type; this means we can update the elements of the
dictionary. We can update the values of the dictionary using keys only; there is no other way
to update the keys of the dictionary.
>>> dict1={1:1,2:2,3:3}
>>> dict1[2]=4
>>> dict1
{1: 1, 2: 4, 3: 3}

 Adding a new key


However, if the key doesn’t already exist in the dictionary, then it adds a new one.
>>> dict1[4]=6
>>> dict1
{1: 1, 2: 4, 3: 3, 4: 6}

3.4.6 Basic Operations on Dictionary


In previous sections we have discussed basic operations of dictionary such as create, update,
delete etc. Other operations are discussed below:

3.4.6.1 Checking the Membership of the element


Checking the membership of the element Sometimes, there is a requirement to check whether
a particular element is part of the dictionary or not. We can check the membership of the keys
as well as the values associated with a particular key in the dictionary using the in or not in
operator. The in operator returns true if the element is found in the dictionary. The not in
operator returns true if the element is not found in the dictionary and it returns false if the
element is found in the dictionary. This is shown in the following examples:

>>> d={1: "Python", 2: "Java" 3: "C Programming"}


>>> 5 in d
False
>>> 5 not in d
True
>>> "Python" in d[1]
True
>>> "Python" not in d[1]
False

M. V. Khasne Data Structures in Python


P a g e | 41

3.4.6.2 Iterating Over the Dictionary


To iterate through a dictionary, we can use the Python for loop. Let’s say, we want to print all
values in a dictionary, then we will use for loop as shown in the below example:
cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
for i in cubes:
print(cubes[i])

Output:
1
8
21
64
125

To print all keys just use for i in cubes: print(i)

To print all the items (key-value) in the dictionary use

for i in cube.items(): print(i)

3.4.7 Nested Dictionary in Python


A normal dictionary is a collection of key: value pairs, and all the keys and their
corresponding values items store unordered. To define a dictionary we use curly braces { }.
Example:
my_dict={"hello":"world","go”: "pro”, "ios":"apple"}

 What is a Nested Dictionary?


When we define a dictionary inside a dictionary is known as Nested dictionary, we can also
say a nested dictionary means a dictionary inside a dictionary.
Example:
nest_dic = {"dict_1":{"hello":"world", "python":"programming"},
"dict_2": {"tech":"geekbuzz", "OS":"window" } }

Behind the code:


In the above code, we have declared a variable nest_dic which is a dictionary by data type,
but we will call it nested dictionary because it has dictions inside itself.

 Create a Nested Dictionary:


Let’s Create 2 dictionaries inside a dictionary:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS',
"price":67000} ,
2: {'Company' :'Samsung', 'model':'Note 10',
"OS":'Android', 'price':87000}
}

M. V. Khasne Data Structures in Python


P a g e | 42

Behind the code:


In the above code, our main dictionary is mobiles and it has two keys 1 & 2, and both the
keys have their own dictionaries as a value.

 Access Elements of a Nested dictionary:


Like a normal dictionary, to access a Nested dictionary we use sq. brackets and the keys to
get the corresponding values. In a nested dictionary, if we want to access the nested
dictionary, values we have to use 2 Sq. brackets pairs.
Example:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS', "price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
print(mobiles [1] ['model'])
print(mobiles [2] ['model'])
print(mobiles [1] ['price'])
print(mobiles [2] ['price'])

Output:
iphone
Samsung
67000
87000

Examples:
 Add Elements to the nested dictionary:

mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS', "price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
#Adding a new dictionary in the mobiles dictionary
mobiles[3] = {}
mobiles[3]['Company'] = 'Nokia'
mobiles[3]['model'] = 'A7'
mobiles[3]['OS'] = 'Android'
mobiles[3]['price'] = 17000
print(mobiles[1])
print(mobiles[2])
print(mobiles[3])

M. V. Khasne Data Structures in Python


P a g e | 43

Output:
{'Company': 'iphone', 'model': 'XR', 'OS': 'IOS', 'price': 67000}
{'Company': 'Samsung', 'model': 'Note 10', 'OS': 'Android', 'price':
87000}
{'Company': 'Nokia', 'model': 'A7', 'OS': 'Android', 'price': 17000}

Behind the code:


In the above example, we add a new dictionary in mobiles, first, we create a new dictionary at
mobiles[3] then place values in that dictionaries with the help of keys.

There is another simple approach to add a dictionary inside a dictionary let’s understand it
with an example:

mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS', "price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
#Adding new dictionary in the mobiles dictionary
mobiles[3] = {'Company':'Nokia', 'model':'A7', 'OS':'Android',
'price':17000}
print(mobiles[1])
print(mobiles[2])
print(mobiles[3])

 Delete elements from a Dictionary.


Python has a keyword del which is used to delete objects, so in a dictionary, we can also
delete its items with the help of this del keyword.
Example to delete an element from a nested dictionary:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS',
"price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
mobiles[3] = {'Company':'Nokia', 'model':'A7', 'OS':'Android',
'price':17000}
del mobiles[1]['price'] # Delete the price key and its value
del mobiles[2]['price']
del mobiles[3]['price']
print(mobiles[1])
print(mobiles[2])
print(mobiles[3])

M. V. Khasne Data Structures in Python


P a g e | 44

Output:
{'Company': 'iphone', 'model': 'XR', 'OS': 'IOS'}
{'Company': 'Samsung', 'model': 'Note 10', 'OS': 'Android'}
{'Company': 'Nokia', 'model': 'A7', 'OS': 'Android'}

Behind the code:


In the above example, we delete the price key and its values for each nested dictionary.

 Delete a nested dictionary.


As we have deleted the price element for each dictionary using del keyword, we can also
delete the nested dictionary using del keyword.

Example:

mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS',
"price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
mobiles[3] = {'Company':'Nokia', 'model':'A7', 'OS':'Android',
'price':17000}
del mobiles[3]
print(mobiles)

Output:
{1: {'Company': 'iphone', 'model': 'XR', 'OS': 'IOS', 'price': 67000
}, 2: {'Company': 'Samsung', 'model': 'Note 10', 'OS': 'Android', 'p
rice': 87000}}

 Iterating Through a Nested Dictionary:


With the help of for loop, we can iterate over the items of nested dictionaries.

Example:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS',
"price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000},
3: {'Company':'Nokia', 'model':'A7', 'OS':'Android',
'price':17000}
}
for i , nes_dict in mobiles.items():
print(i, 'Product information')

M. V. Khasne Data Structures in Python


P a g e | 45

for j in nes_dict:
print(j, nes_dict[j])
print("************")

Output:
1 Product information
Company iphone
model XR
OS IOS
price 67000
************
2 Product information
Company Samsung
model Note 10
OS Android
price 87000
************
3 Product information
Company Nokia
model A7
OS Android
price 17000
************

3.4.8 Built-in Functions on a Python Dictionary


Sr. Built-in
Description Example
No. Function
The len() function returns the length >>> dict1={1:1,2:2,3:3}
1 len() of the dictionary in Python. Every >>> len(dict1)
key-value pair adds 1 to the length. 3
Like it is with lists an tuples, the >>> any({False:False,'':''})
any() function returns True if even False
2 any()
one key in a dictionary has a Boolean >>> any({True:False,"":""})
value of True. True
Unlike the any() function, all() >>> all({1:2,2:'',"":3})
returns True only if all the keys in False
3 all()
the dictionary have a Boolean value >>> all(dict1)
of True. True
The sorted() function returns a sorted >>> dict4={3:3,1:1,4:4}
sequence of the keys in the >>> sorted(dict4)
dictionary. The sorting is in [1, 3, 4]
4 sorted() ascending order, and doesn’t modify
the original Python dictionary. This
function returns the keys in a sorted
list.
Returns the type of the passed >>> type(dict4)
5 type()
variable. <class ‘dict’>

M. V. Khasne Data Structures in Python


P a g e | 46

Built-in Methods on a Python Dictionary


We have already discussed the methods of the dictionary like get(), popitem(),
pop(), clear(), del().

Sr. Built-in
Description Example
No. Method
The keys() method returns a >>> dict1={1:1,2:2,3:3}
1 keys() list of keys in a Python >>> dict1.keys()
dictionary. dict_keys([1, 2, 3])
Likewise, the values() method >>> dict1.values()
2 values() returns a list of values in the dict_values([1, 2, 3])
dictionary.
The copy() method creates a >>> newdict=dict1.copy()
shallow copy of the Python >>> newdict
dictionary. {1:1,2:2,3:3}
3 copy() A shallow copy only copies
contents, and the new construct
points to the same memory
location.
>>> dict1.items()
This method returns a list of
4 items() dict_items([(1, 1), (2, 2), (3,
key-value pairs.
3)])
>>> newdict={3:3,1:1,4:4,9:9}
Removes the last inserted key-
5 popitem() >>>newdict.popitem()
value pair.
(9,9)
This method creates a new >>>
Python dictionary from an newdict.fromkeys((1,2,3,4,7),0)
existing one. To take an {1: 0, 2: 0, 3: 0, 4: 0, 7: 0}
example, we try to create a
new dictionary from newdict.
6 fromkeys() While the first argument takes
a set of keys from the
dictionary, the second takes a
value to assign to all those
keys. But the second argument
is optional.
It is used to set the key to the >>> dict1={1:4,2:6,3:9}
default value if the key is not >>> p=dict1.setdefault(2)
7 setdefault() specified in the dictionary. If >>> print(p)
the key does not exist; inserts 6
the key with specified value.

M. V. Khasne Data Structures in Python


P a g e | 47

3.5 Strings
A string object is one of the sequence data types in Python. It is an immutable sequence of
Unicode characters. Strings are objects of Python's built-in class 'str'. String literals are
written by enclosing a sequence of characters in single quotes ('hello'), double quotes
("hello") or triple quotes ('''hello''' or """hello""").
>>> str1='hello'
>>> str1
'hello'
>>> str2="hello"
>>> str2
'hello'
>>> str3='''hello'''
>>> str3
'hello'
>>> str4="""hello"""
>>> str4
'hello'

Note that the value of all the strings, as displayed by the Python interpreter, is the same
('hello'), irrespective of whether single, double or triple quotes were used for string formation.
If it is required to embed double quotes as part of a string, the string itself should be put in
single quotes. On the other hand, if a single-quoted text is to be embedded, the string should
be written in double quotes.
>>> str1='Welcome to "Sanjivani KBP Polytechnic" of Sanjivani Group'
>>> str1
'Welcome to "Sanjivani KBP Polytechnic" of Sanjivani Group'
>>> str2="Welcome to 'Sanjivani KBP Polytechnic' of Sanjivani Group"
>>> str2
"Welcome to 'Sanjivani KBP Polytechnic' of Sanjivani Group"

A sequence is defined as an ordered collection of items. Hence, a string is an ordered


collection of characters. The sequence uses an index (starting with zero) to fetch a certain
item (a character in case of a string) from it.
>>> myString='hello'
>>> myString[0]
'h'
>>> myString[1]
'e'
>>> myString[4]
'o'

The string is an immutable object. Hence, it is not possible to modify it. The attempt to
assign different characters at a certain index results in errors.

M. V. Khasne Data Structures in Python


P a g e | 48

>>> myString[1]='a'
TypeError: 'str' object does not support item assignment

 Triple Quoted String


The triple quoted string is useful when a multi-line text is to be defined as a string literal.
>>> myString="""Welcome to
Sanjivani KBP
Polytechnic"""
>>> myString
'Welcome to Sanjivani KBP Polytechnic'

3.5.1 Escape Sequences


The escape character is used to invoke an alternative implementation of the subsequent
character in a sequence. In Python backslash \ is used as an escape character. Here is a list of
escape sequences and their purpose.
Escape
Description Example Result
sequence
\a Bell or alert "\a" Bell sound
\b Backspace "ab\bc" ac
\f Formfeed "hello\fworld" hello world
\n Newline "hello\nworld" Hello
\nnn Octal notation, where n is in the range 0-7 '\101' A
\t Tab 'Hello\tPython' Hello Python
Hexadecimal notation, where n is in the '\x41' A
\xnn range 0-9, a-f, or A-F

3.5.2 String Operators


Obviously, arithmetic operators don't operate on strings. However, there are special operators
for string processing.
Operator Description Example
>>> a='hello'
>>> b='world'
+ Appends the second string to the first
>>> a+b
'helloworld'
>>> a='hello'
* Concatenates multiple copies of the same string >>> a*3
'hellohellohello'
>>> a = 'Python
Program'
[] Returns the character at the given index
>>> a[7]
P

M. V. Khasne Data Structures in Python


P a g e | 49

Operator Description Example


>>> a = 'Python
Fetches the characters in the range specified by two Program'
[:]
index operands separated by the : symbol >>> a[7:15]
'Program'
>>> a = 'Python
Program'
>>> 'X' in a
in Returns true if a character exists in the given string False
>>> 'Python' in a
True
>>> 'python' in a
False
>>> a = 'Python
Program'
Returns true if a character does not exist in the given >>> 'X' not in a
not in
string True
>>> 'Python' not in a
False

3.5.3 Converting to String


Python has an in-built function str() which returns a printable string representation of any
object. In the previous chapter we have used int(), float() and complex() functions.
They convert the string representation into integer, float and complex numbers, respectively.
The str() function converts any number to a string object.
>>> str(12)
'12'
>>> str(6+5j)
'(6+5j)'
>>> str(1.11)
'1.11'

3.5.4 String Formatting


Interpolation of objects of different types at placeholders inside a string is called string
formatting. The % operator (otherwise an arithmetic operator used to return the remainder of
division) is used to perform string formatting also. Format specification symbols (%d, %c,
%f, %s, etc) used in C language are utilized as placeholders in a string.
In the following example, name is a string and age is an integer variable. Their values are
inserted in the string with %s and %d format specification symbols, respectively. These
symbols are interpolated to values in a tuple with the % operator in front.
>>> name="Bond"
>>> "My name is %s." % name
'My name is Bond.'

M. V. Khasne Data Structures in Python


P a g e | 50

You can have multiple parameters too.


>>> name="Bond"
>>> age=30
>>> "My name is %s and age is %d years." % (name, age)
'My name is Bond and age is 30 years.'

All C style format specification symbols are permitted.

Format Symbol Conversion


%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x / %X hexadecimal integer (lowercase letters)
%e / %E exponential notation (with lowercase 'e')
%f floating point real number

You can specify the width of integer and float objects. Here, integers a, b and c will occupy
the width of 3 characters in the formatted string. Additional spaces will be padded to the left.

>>> a=1
>>> b=11
>>> c=111
>>> "a=%3d b=%3d c=%3d" % (a, b, c)
'a= 1 b= 11 c=111'

The following specifies the width of the float variable.


>>> percent=55.50
>>> "%5.2f" % percent
'55.50'
>>> "%6.2f" % percent
' 55.50'
>>> "%6.3f" % percent
'55.500'
>>> "%7.3f" % percent
' 55.500'

In the above example, %5.2 specifies the width of float, where 5 is for total characters and 2
is for decimals. So, the result would be '55.50'.

M. V. Khasne Data Structures in Python


P a g e | 51

The width of a string can also be specified. The default alignment is right. For left alignment,
give a negative sign to width.
>>>'%4s' % 'abc'
>>>' abc'
>>>'%6s' % 'abc'
>>>' abc'
>>>'%-6s' % 'abc'
>>>'abc '
>>>a='abc'
>>>'%-6s' % a
>>>'abc '

 format() method
The format() method can handle complex string formatting more efficiently. This method
of in-built string class provides the ability to do complex variable substitutions and value
formatting. This new formatting technique is regarded as more elegant. The general syntax of
the format() method is as follows:
string.format(str1, str2,...)
The string itself contains placeholders {}, in which the values of variables are successively
inserted.
>>>name="Bill"
>>>age=25
>>>"My name is {} and I am {} years old.".format(name, age)
'My name is Bill and I am 25 years old.'
>>>myStr = "My name is {} and I am {} years old."
>>>myStr.format(name, age)
'my name is Bill and I am 25 years old.'

You can also specify formatting symbols by using : instead of %. For example, instead
of %s use {:s} and instead of %d use {:d}.
>>> "My name is {:s} and I am {:d} years old.".format(name, age)
'My name is Bill and I am 25 years old.'

Precision formatting of numbers can be done accordingly.


>>> percent=55.50
>>> "I have scored {:6.3f} percent marks.".format(percent)
'I have scored 55.500 percent marks.'

String alignment is done with <, > and ^ symbols in the place holder causing left, right and
center alignment, respectively. Default is left alignment.
>>> '{:>10}'.format('test')
' test'
>>> '{:<10}'.format('test')

M. V. Khasne Data Structures in Python


P a g e | 52

'test '
>>> '{:^10}'.format('test')
' test '

3.5.5 Built-in String Methods


 capitalize():
Converts the first character of a string to uppercase letters.
>>> mystr='python'
>>> mystr.capitalize()
'Python'

 upper():
Replaces the lowercase characters in a string with corresponding uppercase characters.
>>> mystr='Python'
>>> mystr.upper()
'PYTHON'

 lower():
Replaces the uppercase characters in a string with corresponding lowercase characters.
>>> mystr='PYTHON'
>>> mystr.lower()
'python'

 title():
Returns the string with the first character of each word converted to uppercase.
>>> mystr='welcome to sanjivani kbp polytechnic'
>>> mystr.title()
'Welcome To Sanjivani Kbp Polytechnic'

 find():
The find() method finds the first occurrence of a substring in another string. If not found, the
method returns -1.
>>> mystr='welcome to sanjivani kbp polytechnic'
>>> mystr.find('kbp')
21
>>> mystr.find('xyz')
-1

 count():
The count() method returns the number of occurrences of a substring in the given string.
>>> mystr='welcome to sanjivani kbp polytechnic'
>>> mystr.count('kbp')
1

M. V. Khasne Data Structures in Python


P a g e | 53

 isalpha():
The isalpha() method returns true if all the characters in a string are alphabetic letters (a-z or
A-Z), otherwise it returns false.
>>> mystr='SanjivaniKBP'
>>> mystr.isalpha()
True
>>> mystr='Sanjivani KBP'
>>> mystr.isalpha()
False

 isdigit():
The isdigit() is method returns true if all the characters in string are digits (0-9), if not, it
returns false.
>>> str1='2000'
>>> str1.isdigit()
True
>>> str2='2,000'
>>> str2.isdigit()
False

 islower():
The islower() method returns true if all the characters in the string are lowercase characters,
else it returns false.
>>> str1='python'
>>> str1.islower()
True
>>> str2='Python'
>>> str2.islower()
False

 isupper():
The isupper() method returns true if all the characters in the string are uppercase characters,
else it returns false.
>>> var='SANJIVANIKBP'
>>> var.isupper()
True
>>> var='SANJIVANIkbp'
>>> var.isupper()
False

M. V. Khasne Data Structures in Python


P a g e | 54

3.6 Programs
P1: Python Program to Add Two Matrices

X = [[1,2,3],
[4,5,6],
[7,8,9]]

Y = [[10,11,12],
[13,14,15],
[16,17,18]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

P2: Python Program to Multiply Two Matrices

X = [[1,2,3],
[4,5,6],
[7,8,9]]

Y = [[10,11,12],
[13,14,15],
[16,17,18]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows of X
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

M. V. Khasne Data Structures in Python


P a g e | 55

P3: Python Program to Transpose a Matrix

X = [[1,2],
[4,5],
[7,8]]

result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result:
print(r)

P4: Python program to copy all elements of one array into another array

arr1 = [1, 2, 3, 4, 5]

#Create another array arr2 with size of arr1


arr2 = [None] * len(arr1)

#Copying all elements of one array into another


for i in range(0, len(arr1)):
arr2[i] = arr1[i]

#Displaying elements of array arr1


print("Elements of original array: ")
for i in range(0, len(arr1)):
print((arr1[i]),end=" ")
print()

#Displaying elements of array arr2


print("Elements of new array: ")
for i in range(0, len(arr2)):
print((arr2[i]),end=" ") )

M. V. Khasne Data Structures in Python


P a g e | 56

P4: Python program to print the elements of an array in reverse order

arr = [1, 2, 3, 4, 5]
print("Original array: ")
for i in range(0, len(arr)):
print((arr[i]), end=" ")
print("Array in reverse order: ")
#Loop through the array in reverse order
for i in range(len(arr)-1, -1, -1):
print((arr[i]), end=" ")

P5: Python program to print the duplicate elements of an array

arr = [1, 2, 3, 4, 2, 7, 8, 8, 3]
print("Duplicate elements in given array: ")
#Searches for duplicate element
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] == arr[j]):
print(arr[j])

P6: Python program to print the largest element in an array

arr = [25, 11, 7, 75, 56]


#Initialize max with first element of array.
max = arr[0]
#Loop through the array
for i in range(0, len(arr)):
#Compare elements of array with max
if(arr[i] > max):
max = arr[i]
print("Largest element present in given array: ",max)

M. V. Khasne Data Structures in Python

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy