0% found this document useful (0 votes)
23 views78 pages

Unit 3 Collection and Sequences Chapter 3 (5 August) Final

The document discusses different Python collection data types including strings, lists, tuples, dictionaries and sets. It covers the creation, accessing, updating and built-in methods for each of these data types. The key topics include string formatting, list comprehension, nested data structures, operators for sets and loops for iterating over collections.

Uploaded by

Hariom Jadon
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)
23 views78 pages

Unit 3 Collection and Sequences Chapter 3 (5 August) Final

The document discusses different Python collection data types including strings, lists, tuples, dictionaries and sets. It covers the creation, accessing, updating and built-in methods for each of these data types. The key topics include string formatting, list comprehension, nested data structures, operators for sets and loops for iterating over collections.

Uploaded by

Hariom Jadon
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/ 78

PYTHON PROGRAMMING

PYTHON COLLECTION/SEQUENCES

Authors Gopal Gupta, Harsh Khatter, Shelley Gupta, Poonam Rana, Aatif
Jamshed, Anurag Mishra
Authorized by
Creation/Revision Date May 2021 ,August 2021
Version 1.0
Contents
3. Introduction to collections/sequences data types ........................................................................... 4
3.1 String ................................................................................................................................................ 5
3.1.1 Creation of String ...................................................................................................................... 6
3.1.2 Accessing Strings ....................................................................................................................... 6
3.1.3 Updation / Deletion................................................................................................................. 11
3.1.4 Built-In Method ....................................................................................................................... 12
3.1.5 Basic Operations...................................................................................................................... 16
3.1.6 String Formatters .................................................................................................................... 17
3.1.7 Loop with String ...................................................................................................................... 21
3.2. List ................................................................................................................................................. 23
3.2.1. Creation .................................................................................................................................. 25
3.2.2. Accessing ................................................................................................................................ 25
3.2.3. Update. ................................................................................................................................... 28
3.2.4. Built-in method ...................................................................................................................... 31
3.2.5. Operations with list ................................................................................................................ 32
3.2.6. Loops ...................................................................................................................................... 34
3.2.7 Nested List ............................................................................................................................... 35
3.2.8 List Comprehension ................................................................................................................. 37
3.3 Tuple .............................................................................................................................................. 38
3.3.1 Creation of Tuple ..................................................................................................................... 39
3.3.2 Accessing Tuple ....................................................................................................................... 41
3.3.3 Modification/ Updating a Tuple .............................................................................................. 43
3.3.4 Built-in Methods in Dictionary ................................................................................................ 43
3.3.5 Operations on Tuple ................................................................................................................ 44
3.4 Dictionaries .................................................................................................................................... 46
3.4.1 Creation of Dictionary ............................................................................................................. 48
3.4.2 Accessing of Dictionary ........................................................................................................... 49
3.4.3 Modification in Dictionary ....................................................................................................... 51
3.4.4 Nested Dictionary .................................................................................................................... 53
3.4.5 Built-in Methods in Dictionary ................................................................................................ 53
3.3.6 Loops and conditions on dictionaries ...................................................................................... 55
3.5 Set .................................................................................................................................................. 58
3.5.1 Creation ................................................................................................................................... 59
3.5.2 Accessing ................................................................................................................................. 62
3.5.3 Modification ............................................................................................................................ 62
3.5.4 Built-in-methods ..................................................................................................................... 64
3.5.5 Operators ................................................................................................................................ 68
3.5.6 Loops ....................................................................................................................................... 74
3.5.7 Frozen Set................................................................................................................................ 75
3.6 Summary ........................................................................................................................................ 77
References: .......................................................................................................................................... 78
3. Introduction to collections/sequences data types
In chapter 1, we have seen some primitive data type like: integer, float and complex. These
data types are used to represent the single value numeric data and in chapter 2, we have
learnt to apply condition, loop on this type of data but in real life we need to store data like-

• Name of students – A sequence of alphabet character


• Marks of n students – A sequence of either integer or float value
• Student’s record – A sequence of name, branch, roll number, address etc.
So, to represent these type of data Python provides us some built-in collection data types as
shown in figure 3(a).

Figure 3(a): Collection / Sequences Data Types

Figure 3(b) String, List, Tuple and Dictionary


If data is the combination of numeric data, alphanumeric or of different types than we go for
List, Tuple or set as shown in figure3(b). If data is in the form of key-value pair than we go for
dictionary.

All collection data types in python have rich variety of built-in method and associated
operation.

Built-in method are such functions or procedure which provides us to use as plug and play,
we do not have to implement it.

3.1 String
Suppose we want to store a name of college, About the college or Address of college then we
choose String data type. A string is a sequence of alphanumeric and special character.

Alphanumeric characters: a-z, A-Z, 0-9; Special symbol: *, -, +, $, @, whitespace …. etc

For example - 'abes', 'Computer Science', '123', 'NH-24, Delhi Hapur Bypass' are the string.

String is the collection of characters, it may compose of alphanumeric and special characters.
In Python, Strings are created in many ways using single quotes or double-quotes.

Figure 3.1 string represented using single or double quotes

Note - Python does not have char data type, so if we have to take one char variable so it
means we have to take a string of length 1.

This section discusses about the string in python, operations and built-in methods on string.
3.1.1 Creation of String
Empty String
An empty string is a string having no character. We have three ways to create an empty
string as shown in syntax.
Syntax –

Figure 3.1.1(a) Syntax of empty string

In Figure 3.1.1(a), an empty string is created by using single quotes, double quotes and str().

Non Empty String


A non-empty string is a sequence of alphanumeric character with at least one character.
Syntax -

Figure 3.1.1(b) Syntax of non-empty string

In Figure 3.1.1(b), a non-empty string is created by using single quotes and double quotes.

3.1.2 Accessing Strings


Strings element can be accessed using square brackets. These square brackets [] take an
index as input.

Syntax –

In python we have two types of Indexing:


• Positive Indexing
• Negative Indexing

Positive Indexing

In python positive indexing start from Zero (0) and from left hand side i.e. first character
store at index 0, second at index 1 and so on.

Figure 3.1.2(a) Positive Indexing

As shown in figure 3.1.2(a) positive indexing start from left-hand side and start from Zero
(0). Every character of string has some index value.

Negative Indexing

In python negative indexing start from -1 and from right-hand side i.e. Last character store at
index -1 and as we move towards the left, it keeps increasing like -2, -3, and so on, as shown
in Figure 3.1.2(b).

Figure 3.1.2(b) Negative Indexing


Example 1 - Write a program to print character 'P' and 'L' using positive indexing and
negative indexing. Assume a string st = 'I Like Python’, is given.

In the above example index of 'L’ is 2(positive) and -11 (negative), index of 'P' is 7(positive)
and -6 (negative).

Note – We can use both positive and negative indexing to access any element/ character from string.

We have already seen that using [], we can access string characters by giving indexes if we
use colon inside square bracket like [:] it becomes a slicing operator in Python.

String slicing is the way of selection of substring, as shown in figure 3.1.2(c). String 'Like' is
substring in given 'I Like Python' string.

Figure 3.1.2(c) Sub String


Syntax -

Figure 3.1.2(d) Syntax of Slicing

Examples - Let’s assume string st = 'I Like Python' is given.

Table 3.1.2: String slicing and examples

Example Explanation Example


It starts with the 2nd index

st[ 2 : 6 ] and ending with (6-1=5)th


index.

It starts with index 0th and


end with (6-1=5) th. Step is 2
st[ 0 : 6 : 2 ]
So, it will give value at index
0,2,4
It starts slicing from 12th
index up to 6-1=5th index. 12th
st[ 12 : 6 : -1]
to 6th in opposite direction
because step is negative.
It starts with -11th index and

st[ -11 : -7 ] ending with (-7-1 = -8)th


index.

The operator gives the

[:] complete original string.*

Start index is missing and step

[:6] is +1, So it will start from 0 till


6-1=5th index.*

It will start from index 7 to

st[ 7 : ] last index ( Last index missing


)*

Step is -1, So start index will


be the last index and end
st[ : : -1]
index will be first index when
start and end is missing.
This is explaining in Note

st[ 2 : 6 : -1 ] Section **
Output – Empty string

Note – *, **

• * When start index is missing it will start from either first character or from last. It
depends on step sign (positive or negative).
• * When end index is missing it will execute till last character or first character. It
depends on step sign (positive or negative).
• * When we take negative steps it will scan from start to end in opposite direction.
• ** In the case of step is positive or negative the slicing will be done as below given
algorithm.

When Step is Positive When Step is negative


st [ start : end : +1 ] st [ start : end : -1 ]
Working of slicing Working of slicing
i = start i = start
while i<end: while i>end:
//do scanning //do scanning
i = i +1 i = i -1
Example – Example –
st[6:2:1] st[2:6:-1]
i=6 i=2
while i < 2: while i > 6:
//do scanning //do scanning
i = i +1 i = i -1
Expression i<2 will evaluate to False and i>6 will evaluate to False and loop will
loop will terminate and empty string terminate and empty string will be slice.
will be slice.

Practice Questions:
1. Write a program to reverse a string and check it is palindrome or not.
2. Write a program to capitalize the first and last character of each word in a string.

3.1.3 Updation / Deletion

Updation

Strings in python are Immutable(un-changeable) sequences, which means it does not


support new element assignment using indexes. Let's try this in the following example 1.
Example 1 – Write a program to reassign first character.

In above Example 1, as we can see, the string does not allow assigning a new element,
because item assignment does not support by string.

Deletion

We can’t reassign the string characters but we can delete the complete string using del
command as shown in the example 2.

Example 2 – Write a program to delete string object.

As we can see in the example 2, after deletion when we try to print the string st it gives
NameError : st not defined.

3.1.4 Built-In Method


String supports a variety of Built-In methods for achieving different types of functionalities.
All built-in methods provide us to use as plug and play, we do not have to implement it. In
python methods are called using dot(.) operator as shown in figure 3.1.4
Figure 3.1.4: Calling Built-in method

Note - There are few generic built-in methods which are not called by dot operator. These methods
are used by all collection (string, list, tuple, set etc.) in python. These methods are called by their
name and we pass collection as argument.

All such string associated methods are listed in below table.


Table 3.1.4: String Built-in Methods and examples
Method
Explanation Example
Name
Return a string with first letter
capital
capitalize()
e.g.
i like python à I Like Python
Return string in lowercase
casefold()

Return the number of occurrence


of substring.
• In the first example “i”
count() occurred 3 times.
• In the second example “like”
occurred 2 times.

Return True if the string ends with


endswith() the given substring otherwise
return False.
Returns True if the string starts
with the given substring otherwise
startswith() return False.

Return the lowest index in String


where substring sub is found.
find() In example – there are two “like”.
1st “like” is at index-2 and 2nd at
index-16. It return 2.
Convert and return a string into
lower case
lower()

Convert and return a string into


upper case
upper()

In swaps cases, the lower case

swapcase() becomes the upper case and vice


versa

Converts the first character of each


word to upper case.
title()

Returns a string after replacing old


replace() substring with new substring.
Splits the string from given
separator and returns a list of
substring.
Note –
split()
• By default, value of separator is
a whitespace
• List will be discussed in section
3.2
Concatenate any number of strings.
The string whose method is called is
join()
inserted in between each given string.
The result is returned as a new string.
Return a copy of the string with

strip() leading and trailing whitespace


removed.

Return true if the string is


alphanumeric ( Combinition of a-z,
A-Z, 0-9)
isalnum()
Note – It will return false only if
string conatins special character.

Return true if the string contains


only alphabets(Combinition of a-z,
A-Z)
isalpha()

Returns True if all characters in the


isdecimal() string are decimals
Returns True if all characters in the
string are lower case

islower()

Returns True if all characters in the


string are upper case

isupper()

Returns True if all characters in the


string are digit

Isdigit()

Return length(No of character) of a


len() given string. This is a generic
function.

Practice Questions:
1. Write a program to remove ith character from a given string.
2. Write a program to find a string contains only alphabets.

3.1.5 Basic Operations

Strings in Python support basic operations like concatenation, replication and membership.
• Concatenation means joining/combining two string into one.
• Replication means repeating same string multiple times.
• Membership tells a given string is member of another string or not.
All Operations are being summarized in the following table 3.1.5.

Table 3.1.5: String operations and examples


Operator Explanation Example
Concatenation

+
It will merge/join second string at
the end of first string and return.
Multiply (Replicas)
It will repeat same string multiple
* times and return.
Note – multiply string only with
integer number.
Membership
It will check a given substring is

in present in another string or not.


Note – gives bool value
(True/False)

not in It's reverse of Membership

3.1.6 String Formatters

For different types of requirement to print the string in a formatted manner; here, format
implies that in what look and feel we want our strings to get printed; python string provides
a number of options for formatting.
Table 3.1.6(a): String format style
Escape Explanation Example
sequence
Ignores newline

\newline

Backslash

\\
Write a backslash in string

If we need to use single


\'
quotes in our string like
Good Morning! Mr. 'BOB'
If we need to use double

\" quotes in our string like


Good Morning! Mr. 'BOB'

Newline

\n

The format () method


This method is a beneficial method for formatting strings; it uses {} as a placeholder, as shown
in the below example. We have placed two curly braces and arguments that give the format
method filled in the same output. Figure 3.1.6(a) shows example of same.

Figure 3.1.6(a): Usage of format in the string


If we want to change the order of arguments, we can give an index of parameters of format
method starting with 0th index as shown in the figure, as shown in figure 3.1.6(b).

Figure 3.1.6(b) Usage of argument in format

We can also use keywords arguments in format method, as shown in the following example,
as shown in figure 3.1.6(c).

Figure 3.1.6(c): Usage of keyword argument in format

We can also use format specifier in format method like in language ‘C’. Format specifier are
used to do following –
• Represent value of amount = 12.68456 at two decimal place
• Represent value of integer in Binary, Octal or Hexadecimal etc.
Syntax -

Figure 3.1.6(d): Syntax of format specifier


In the above example, b is used for binary representation. The below table show the list of
format specifier.

Table 3.1.6(b): format specifier


Format Explanation Example
Specifier
Use for Binary
b

Use for Octal

Use for Hexadecimal

X or x

Use for Decimal


d

Use for Float


Note – Place .n before f, for
f representing floating point
precision. n is decimal
places.

Formatting using fstring

Fstring is the way of formatting as format method does but in an easier way. We include ‘f’
or ‘F’ as a prefix of string as shown in below example.
Figure 3.1.6(e): Usage of fstring

In the above example, value of a, b and c are place at given {}.


Practice Questions:
1. Write a program to take input principle, amount, rate of interest and calculate
Simple Interest and print it at precision 2.
2. Write a program to take your name as input and print the statement “Good
Morning! Your Name”

3.1.7 Loop with String

Strings are sequence of character and iterable objects, so we can directly apply for loop
through string.

Example 1 - Scan/Iterate each character of string through index using for loop.

In the above example, with the help of range () function first generate sequence of index and
apply loop.
Example 2 - Scan/Iterate each character of string directly using for loop.

In the above example, for loop apply directly to string st. for loop iterate using ‘val’ variable
and each character is referring one by one via val. Using print statement, we print the value
of val.

Example 3 – Write a program to print number of alphabets and digits in a given string.

Example 4 – To add 'ing' at the end of a given string (length should be at least 3). If the given
string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less
than 3, leave it unchanged.
Sample String : 'abc' Sample String : 'string'
Expected Result : 'abcing' Expected Result : 'stringly'
Practice Questions:
1. Write a program to find the frequency of vowels in a given string.
2. Write a program to find number of special symbol in a given string. Whitespace
should be ignored.

3.2. List
In Python List is the most commonly used sequence. Important points about list are as
follows.

• List elements are enclosed in square brackets [] and are comma separated.
• List is the sequence of class type ‘list’.
• List can contain elements of different data types.
• List is a mutable(changeable) sequence, would be discussed in detail in 3.2.3
• List allows duplicate elements.
• List elements are ordered, it means it give specific order to the elements, if new
element is added, by default it comes at the end of the list.

List is used when there is a possibility of elements of different data type, for example record
of a particular student, having name as string, roll.no as integer, marks as float, father’s
name as string. To contain this record list is the appropriate sequence.
Figure 3.2: List representation

List example

In this example a variable named listexample has been created and three elements have
been assigned. As we have enclosed elements in square brackets, this makes listexample is
of type list.

Ordered property of list:

Ordered sequence of the list means the order in which elements appear is unique and the
position of every element is fixed; if we change the position of any element, then list would
not be the same anymore. Let's verify this with an example.
3.2.1. Creation
List can be created in many ways as follows

Empty list

As shown in following example, we can create empty list using following two methods.

Non Empty List

After empty list, we have created list with elements.

3.2.2. Accessing
List elements are accessed using indexes.

• Indexing
In the list index are started from 0, it means first element takes 0 index and it
increases like 0,1,2…(n-1). List also supports negative indexing, it means last element
can be accessed using -1 index, second last as -2 and so on. These indexes are as
shown in figure 3.2.1.
Figure 3.2.1 Positive and Negative indexes in the list

• Slicing
As we have seen in the string section that slicing is used to get substring from a
string. We use Slice operator in the list to get a sub list.

Syntax of slicing

Figure 3.2.2 Syntax of List slicing

Start= Optional argument by default value is 0.


End = Optional argument by default value is number of elements in the list. If any
number given, then value is taken as number-1.
Step=Options argument by default value is 1.
Colon 1: Required
Colon 2: Optional
Example
In this example a list has been taken and different slicing has been performed.
• In first and second case only single colon and double colon has been used and as we
can see in corresponding output original list has been printed.
• In third case we have taken start value 2, which indicates take value of list from
index 2 and in result, we get elements from index 2 till last.
• In fourth case we have set start and end both as 2 and 5, so it’s starting from 2 and
ending with (5-1) and printing values for indexes 2,3 and 4 index.
• In fifth case start, end and step has been set as 2,5 and 2. So output substring
starting from index 2, ending with 5-1=4 and step counter is 2, so its skipping
alternate element.

Few more examples of list slicing

Operator Explanation Example


[:] This gives a
complete original
list
[1:3] It starts with 1th
index and ending
with (3-1=2)
index
[2:] Sublist starts with
index 2 and ends
at last element as
nothing specified
on right side of
the colon
[1:4:] Start=1, stop=4
and by default
step=1.

[1:4:2] Start=1, stop=4


and by step=2. As
the step is 2, it
took every 2nd
element.
[::-1] Starting is 0th
index and
stopping at last
index and step is
negative count so
that it would
print in reverse
order

3.2.3. Update.
List updating involves insertion of new elements, deletion of elements or deletion of
complete list.

Mutable

List is a mutable sequence it means it allows changes in the elements of list as shown in
figure 3.2.3
Figure 3.2.3 Mutability Vs Immutability

Add new element

We can add elements to the existing list using append function. Append function always add
the element at the end of the list.

Syntax:

Listname.append (element to be added)

Example: In this example element 5 has been appended in the originally existed list. It’s
being added in the last.

Changing an element of list

Value of the element at index 3 has been assigned new value as 5, so element in the output
list is changed from 4 to 5
Deletion from list

List elements can be deleted

• Using del command If we know the position(index) of the element which is to


be deleted.
• We can use the remove method by giving the specific element as given in the
example If we know the position(index) of the element.

Example:

In this example list element has been deleted using del and remove.

Complete List deletion

In following example list1 has been deleted and then we are trying to print it and its giving
error because it does not exist now.
3.2.4. Built-in method
Python provides many built-in functions for different useful functionalities.

Method Remark Example


len() It calculates the length of the list or
the number of elements in the list

max(list) It returns the maximum element


from the list

min(list) It returns a minimum element from


the list

list(seq) It converts into any sequence into a


list
pop() It deletes the last element from the
list
Note – We can also pass index as
argument in pop() to delete a specific
index value.
count() It counts the occurrences of a
particular element in the list

sort() Sort the elements of the list in


ascending order

reverse() Sort the elements of the list in


reverse order

3.2.5. Operations with list

Python supports a variety of operations for the list.

Table 3.2.5: List operations and examples

Operation Remark Example


Operation
adds two
Concatenation
list
elements
It repeats
the list
Repetition specified
number of
times
To check
whether
an
Membership element
belongs to
the list or
not
I return
true of an
Membership- element
Not that does
not belong
to the list

Example Exercise with Solution

Exercise: Write Python program to swap elements in the list

Solution:
Practice Exercise

1. Take a list input from user having integer elements and calculate sum and average
of the list.
2. Take an input list and swap string elements of the list with empty string.

3.2.6. Loops
We discussed loops in chapter 2. Now we would see how loop works with List sequence.

While loop with List

Using while loop we can read the elements of list as shown in following example

For loop with List

Let’s see how list elements can be accessed using for loop

We can clearly see in both the above examples that for loop requires less effort in printing
element in comparison of while loop.
Example Exercise with Solution

Exercise: Write a python program to print all positive number of a list

Solution:

Practice Exercise:

1. Write a python program to remove duplicate from the list.


2. Write a python program to count positive, negative and string type elements.

3.2.7 Nested List


When we have an element of a list in the form of the list itself, it is called Nested List. Elements
of the nested list can be accessed using the 2-D indexing access method.

In this example, first [1] denotes [3,4] and second [1] represents 4, so it gives output as 4.
Nested List as a Matrix

We can represent nested list as matrix also. For this we would use nested for loop. Outer
loop would run for number of elements in the list and inner loop would consider individual
element of the nested list as a list.

In this example value of outer loop is running three times and value of i is 0,1 and 2 while
inner loop element is being accessed using j which takes values 0,1 and 2.

Example Exercise with Solution

Exercise: Create a flat list from given nested list

Solution:

Practice Exercise:

1. Using nested list print transpose, of a given matrix


2. Print reverse order of a nested list
3.2.8 List Comprehension
Let's suppose we want to write a program to calculate powers of 3 for a given range; let's
solve this as shown.

Python provide us writing iterative programs in much lesser lines called List comprehension.
The same problem has been solved using list comprehension.

Syntax:

[ statements for an item in list ]

Conditional in a list comprehension

we have the facility of adding conditionals in the list comprehension

We can add if-else as shown in the example, we should notice one change that because in if-
else case output is separated based on the condition, if-else and conditions has been
written along with statements.
Example Exercise with Solution

Exercise: Add 30 to every element of an integer type list if its odd and add 40 if it’s even

Solution:

Practice Exercise:

1. Convert each element of a given list of type string into upper case using list
comprehension.
2. Calculate cube of every element of integer type list using list comprehension.

3.3 Tuple

Tuple is an immutable (unchangeable) ordered collection of elements of different data types.

Generally, when we have data to process, it is not required to modify the data values. Take
an example of week days, here the days are fixed. So, it is better to store the values in the
data collection, where modification is not required.
Figure 3.3 Tuple Representation

In the above figure 3.3, the round brackets are used to define a tuple. If we want to change
any of the index value in tuple, this is not allowed and throw an error.

3.3.1 Creation of Tuple


A tuple is created when elements are placed in a comma-separated manner enclosed within
parenthesis. Tuple can have any number of elements, and they can have a different datatype.

Empty Tuple:

Syntax:

Let have a look to the creation of empty tuple:

Figure 3.3.1(a) Syntax of empty Tuple using ()

In above example, the () round brackets are used to create the variable of tuple type. We
can also call the class to create a tuple object as shown in example below.

Figure 3.3.1(a) Syntax of empty Tuple using tuple ()


The creation of a tuple of a single element is a bit untraditional, let's see.

Non Empty Tuple:

Syntax:

Figure 3.3.1(b) Syntax of Non empty Tuple

Example 1: Write a program in python to create one element in tuple.

In above example 1, If you want to create a tuple with single value, it is required to add a
comma after the single value as shown in the above example c=(‘college’,). If the comma is
not placed, then the single value a= (1) or b=(ABES) will be treated as an independent value
instead of the data collection.

Packing and Unpacking of Tuple:

Tuple can also be created without using parenthesis; it is known as packing, as shown in the
example.

Example 1: Write a program to create tuple without parenthesis.


In above example 1, newtup4=3,4,5,” hello” creates a new tuple without parenthesis.

Example 2: Write a program to unpack elements in tuple

Unpacking is called when the multiple variables is assigned to a tuple; then these variables
take corresponding values.

In above example 2, a,b,c,d =newtup4 unpack the elements into variables.

Practice Questions:

• Write a Python program to create the colon of a tuple.


• Write a Python program to unpack a tuple in several variables.

3.3.2 Accessing Tuple


Tuple elements can be accessed using indexes, just like String and List as already shown in the
sections 3.1 and 3.2. Each element in the tuple is accessed by the index in the square brackets
[]. An index starts with zero and ends with (number of elements - 1)

Example1: Write a program to access index 1 element from tuple.


In above example 1: tuple newtup carries multiple types of data in it as “hello” is string, 2 is
integer, and 23.45 is float. If we can fetch the index 1 element using print(newtup[1]).

Example2: Write a program to access index 0 element from tuple.

In above example 2: tuple tuple_days carries the day’s data in it. If we can fetch the index 0
by using print(tuple_days[0])

Example3: Write a program to access index -1 element from tuple.

Basically, the -1 index will return the last value of tuple. Indexes start from zero, and it goes
up to a number of elements or say -1. Take another example to fetch the -1 index from
tuple.

In above example 3: last element is accessed by print(tuple_days[-1]).

Indexing in Tuple and Slicing

Slicing in a tuple is like a list that extracts a part of the tuple from the original tuple.

Example1: Write a program to access elements from 0 to 4 index in tuple.

In above example 1: The elements are accessed by print(tuple_days[0:4]).


Example2: Write a program to access elements from 1 to 3 index in tuple.

In above example 2: The elements are accessed by print(newtup[1:3]).

3.3.3 Modification/ Updating a Tuple


If we want to change any of the index value in tuple, this is not allowed and throw an error.
Tuple object does not support item assignment. Here, we are taking the same above example
of days and showing the immutable characteristic of tuple.

Note: Tuples are immutable

Practice Questions:

• Write a Python program to get the 4th element and 4th element from last of a
tuple.
• Write a Python program to check whether an element exists within a tuple.

3.3.4 Built-in Methods in Dictionary

Tuple has two methods, as shown in the table.


Table 3.3.4 Methods in Tuple

Method name Remark Example


count() It returns the
occurrences of
the value
given
index() It returns the
index of the
specified value

3.3.5 Operations on Tuple

The list of operations allowed on tuple which are frequently used are shown below in form
of table:

Operations Remarks Example

Add two
Concatenation
tuples

Creates
Multiplication copies of the
tuple

To check
whether an
Membership element
belong to
tuple or not
Would return
Not true if
element does
Membership
not belong to
tuple.
Practice Questions

• Write a Python program to count the elements in a list until an element is a tuple.
• Write a Python program to calculate the average value of the numbers in a given
tuple of tuples

3.3.6 Loops and conditions on tuple

Tuple can be traversed using loop.

Example1: Take the tuple named tuple_days and print all its elements.

In above example 1: The elements are printed while iterating through for loop condition for
in tuple_days and then we print the values of i in each iteration.

Example2: Let have a look to the example where we are placing a condition to return the
values having word length greater than 3.

In above example 2: The elements are printed while iterating through for loop condition for
in tuple_days and then we print the values of i in each iteration with the condition if(len(i)>3)

To show the comparison between list and tuple, have a look to the table below:

Table3.3.6: List vs. Tuple


List Tuple
Mutable Sequence Immutable Sequence
Accession Slower than Tuple because of Faster access of elements due to
mutable property immutable property
It cannot be used as Dictionary keys Can work as a key of the dictionary
Not suitable for application which needs It suits such scenarios where write
write protection protection is needed.

Practice Questions:

• Write a Python program to convert a tuple of string values to a tuple of integer values
• Write a Python program to convert a given tuple of positive integers into an integer.

Example Exercise with Solution


Exercise: Write Python program to join two input tuples, if their first element is common.
Solution:

3.4 Dictionaries

Dictionary is a unique data collection of Python which stores the key-value pair.

In the list, the values are stored based on the integer default indexes. The indexes are by
default and start with index 0. As the list shown in figure 3.4(a), the indexes and values of the
list are mentioned.
By default,
indexing in list

Figure 3.4(b): list elements in memory

In above example, 0,1,2,3,4 are the by default indexes and 1219, “harsh”, “M”, “CSE-2”,
“ABES” are the corresponding values in the list. If I talk about the value 1219, user is unaware
about the value, what exactly 1219 is? Is it a roll number, or faculty number, or library card
number! So, it is better to have an attribute name which represents the value.

Dictionary provides the solution to the above problem. The user can add an element by giving
a user-defined index called a key. And the key and its corresponding value makes the key-
value pair in dictionary. This key-value pair is considered as one item in dictionary.

Figure 3.4(b) shows the dictionary orientation where on the left side, keys are present
concerning the values on the right side of the figure.

Figure 3.4(b): Dictionary elements in memory

In dictionaries, the indexes are not by default. Users can create its customize indexes named
as keys and store their respective values. Here in the above example, dictionary has three
key-value pairs. “Emp code” is the key and its value is 1219. “Name” is a key, and its value is
“Harsh”. These key-value pairs is written as {“Emp code”: 1219, “Name”: “Harsh”, “College”:
“ABES”}.

Note: {} is the representation of Dictionary


3.4.1 Creation of Dictionary
To create a dictionary, a dictionary class object can be created like

Empty Dictionary

Syntax

Figure 3.4.1(a): Empty Dictionary

Figure 3.4.1(a) shows the creation of empty dictionary.

Example 1: Write a program to create empty dictionary

In above example 1, dict is used to create empty dictionary when we print the dictionary, it
will represent a blank dictionary with symbol {}.

Non-Empty Dictionary

Syntax

Figure 3.4.1(b): Non-Empty Dictionary


Another way is to create a dictionary with its key-value pair where we need to pass the key
and its value within curly brackets to define a dictionary.

Example 1: Write a program to create non-empty dictionary

In the above example 1, dictionary creation with keys: name, empcode and subject and their
values.

3.4.2 Accessing of Dictionary


In other data collections, the accessing of an element is through the index. But in dictionary,
the items are accessed by the keys.

Example 1: Write a program to access element values from a dictionary using element keys.

In above example 1 a dictionary d is created with key value pairs. If you want to fetch the first
value i.e. ‘Harsh’, so you need to mention the key of the value like d[‘name’], here the name
variable is in string format so quotes are required; without quotes, the statement will give an
error.

Example 2: Write a program to access value from key.


In above example 2 dic1 is the name of dictionary object having three key items. If you write
dic1[‘a’] Output is produced as “python”.

If the syntax is like a list, where the index is used to get the element value, i.e. dic1[0], it will
give a key error. Here, the value will be retrieved from dic1["a"].

The example is shown below.

The accessing style in list and dictionary is different. If we compare the functionalities of list
and dictionary, then the outcome is shown in figure 3.4.2(a).
List Dictionary

By Default User defined Keys


indexing

Indexes are only of Keys can be of any


integer type type

Adds an element to Adds an element to


the next default the user defined
index key location

Fetching of Fetching of value


element is through is through keys,
index, lst[0] dic[<key>]

Traversing is easy Traversing is easy


just by increase the just by increase the
index, i+=1 index, i+=1

Figure 3.4.2(a): Accessing difference between List and Dictionary

3.4.3 Modification in Dictionary

When we store some values in the collection, we must need a liberty to modify or update its
value. In dictionary, we have an option to modify or update the values. The values can be
easily changed by giving the key as index with dictionary name.

Example 1:

Here the initial value of name is ‘Harsh’. If we want to change the value to ‘Harsh Khatter’,
then the key ‘name’ is to be passed in dictionary d with updated desired value.
Example 2: Take an example to swap the values of the dictionary.

Here the dictionary values are swapped by using the keys and temporary variable.

Is it possible to change the keys?

No, if we try to change the key, interpreter will create a new key. Once the keys are defined,
it is not possible to change the keys; we can change or update the values with respect to the
keys only.

Example: where we are trying to modify the existing key ‘name’ as the ‘firstname’. But instead
of updating the existing key, a new key ‘firstname’ has been added to the dictionary with
same given value ‘Harsh’.
Note:
1. In dictionary, keys are not changeable, only values are modifiable. It means
“Keys are immutable, and the values are mutable”
2. Keys are unique, and the values of the keys can be same

3.4.4 Nested Dictionary


As we have the option of a nested list, similarly, dictionaries can consist of data collections.
See an example to create a nested dictionary.

Here, the dictionary dt is created in such a manner where the key 3 consists of an another
dictionary. If you want to fetch the inner dictionary value, use the same concept of nested
list.

3.4.5 Built-in Methods in Dictionary

dict.copy( ) - Copying a dictionary into another dictionary

dict.fromkeys() – When the keys are already in a data sequence, and a new dictionary with
the keys from the data sequence is created with new values. Here, the below example shows
how a list of values is used as the dictionary's keys to save the data values.
dict.get() – If the key is present in the dictionary, its value is returned. If the key is not present
in a dictionary, then the default value will be shown as output instead of a KeyError. get()
method has an option to add a default value.

dict.items() – this will return the key-value pair as an output.

dict.keys() – this will return only the keys as an output.

dict.values() – this will return only the dictionary values as an output.

dict.update() – this adds the one dictionary with another dictionary. Here in the example, the
dictionary dict2 is added to dict1 dictionary.
dict.pop() - The pop() method takes an argument as the dictionary key, and deletes the item
from the dictionary.

dict.popitem() - The popitem() method retrieves and removes the last key/value pair inserted
into the dictionary.

3.3.6 Loops and conditions on dictionaries

Loops and conditions can easily apply to dictionaries. Let's look at the loop and conditions in
dictionary.

Example: Iterate dict.keys()


Example: Iterate dict.values()

Example: Iterate dict.items() to fetch key-value pair

Example: Find a key in dictionary

Example: Find a key in dictionary, here "Python" is value


Example: Find a value in dictionary

Example: Find a key in dictionary using dict1.keys()

Example Exercise with Solution


Exercise: Write Python program to create dictionary having keys from 1 to 5 and values as
their squares.
Solution:

57
3.5 Set

A set is another data collection data types in python, which stores unique elements in an
unordered way.

Unordered: Not arranged in any order as shown in figure 3.5.

Ordered Unordered
1.Item 1 1. Item 2

2. Item 2 2. Item 5

3. Item 3 3. Item 1

4. Item 4 4. Item 3

5. Item 5 5. Item 4

Figure 3.5 Ordered vs unordered

Scenario 1: In ABES Engineering college, we have different sets of rules which have to follow
by every student and employee. There are disciplinary rules, rules for leave, hostel rules,
Timing rules, and many others. Hence, all different types of rules are separated from others
and can be stored in the form of set.

Scenario 2: When we visit any shopping mall, we all have noticed that there are separate
portions or sections for each kind of things. For instances, clothing shops are on another floor
whereas the food court is at another floor of the mall so these categories can be considered
as sets.

Scenario 3: In a class of 50 students, 35 said they loved Python, 30 said they loved Java. The
teacher wanted to know how many students loved both Python and Java, as well as those
who did not have a hobby. The teacher grouped the students who had Python and Java into
groups called sets.

Note: Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.

58
3.5.1 Creation

Empty Set

To create an empty set we have to use set ()

Syntax:

Figure 3.5.1 Syntax of Set ()

Set can be created using class name set () and elements can be stored in assigned set s1
object/variable as shown in a figure 3.5.1

Example 1: Write a program to create empty set.

In above example 1, an empty set is created using set() and set without any elements are
produced as output using print(s1). print(type(s1)) is used to check the class of s1 variable
/object.

Note: To define an empty set, we cannot use the curly braces {} , because dictionary also
uses curly braces to create empty dictionary.

59
Example 2: Write a program to create set using {}.

We can not create


empty set using {}
brackets

Output

In above example 2, we have tried to create empty set using {} and it returns dictionary as
output.

Non Empty Set

The elements in non-empty sets can be of any types like numbers, float, strings, Boolean etc

In Python, the elements of a non-empty sets are defined inside curly braces {} and are
separated by commas.

Example 1: Write a program to create non empty set of integers.

In above example 1, set of integers is created using curly brackets and unique elements are
produced as output.

Example 2: Write a program to create non empty set of strings.

Elements as String

Output

In above example 2, set of strings is created using curly brackets and unique elements are
produced as output.

60
Example 3: Write a program to create non empty set of different data types.

In above example 3, set of Integer, Float, strings and Boolean is created using curly brackets
and unique elements are produced as output.

We can also create non empty et using set(object), which iterates over the elements present
in object and adds all the unique elements to the set as shown in examples below.

Example 4: Write a program to create non empty set of integers as list.

In above example 4, set of integers in list are passed as argument in set () as an object and
unique elements are produced as output.

Example 5: Write a program to create non empty string.

In above example 5, set of characters as string is passed as argument in set() as an object and
unique alphabets are produced as output.

61
3.5.2 Accessing

Python set’s item cannot be accessed using indexes. The elements in set appear in a different
order every time it is used. Due to this, set elements cannot be referred to by index.

Example 1: Write a program to access any element in set.

Output

In above example 1, we try to access set_acess[2] and it will give us a Type Error (‘set’ object
does not support indexing )when using indexing.

3.5.3 Modification
Every element in a set is unique and immutable(unchangeable), i.e. no duplicate values
should be there, and the values can’t be changed.

Example 1: Write a program to modify existing element in set.

Output

In above example we are trying modify element(set_access[2]=4), it will give type error(set
does not support item assignment).

However, we can add or remove elements from the set as the set itself is mutable.

62
We use the add () method to add a single element and update () method when multiple
elements are to be added. The elements can be of the form lists, tuples, strings, or sets in
the update () method. Duplicates are avoided in all cases.

Add() Method

Python set add () method is used to add an element to the given input set. If the element
already exists, then the add () method does not add the element.

Syntax:

Method This is a required


Name parameter. It defines the
element to add to the set.

Figure 3.5.3(a) Syntax of add()

Example 2: Write a program to add new element in set.

In above example 2, we are trying to add new element by set_add.add(22), it will add up new
element 22 into existing set.

Update() Method

Python set update () method is used to update the current set by adding items to it from
the another set. If an item is present in both sets then only one appearance of this item
will be present in the updated set.

63
Syntax:

Figure 3.5.3(b) Syntax of update ()

Example 3: Write a program to add multiple elements in a set.

In above example 3, we are trying add new elements by set1.update([22,13,14]),


set1.update([14,15].{11,16,18}) it will add up new and unique elements into the existing set.

Practice Questions:

• Can we update tuple and dictionary inside set?


• Difference between add () and update().

3.5.4 Built-in-methods
There are more than 15 Python set of built-in methods that can be used on sets. Some of the
important and frequently used methods will be discussed below.

add() and update() method have been covered already in previous section 3.5.3.

64
Clear() method

Python set clear () method is used to remove all the elements in the given input set.

Syntax:

Figure 3.5.4(a) Syntax of clear ()

Example 1: Write a program to remove all elements from a set.

In above example 1, we are trying to remove all elements by set1.clear(), it will remove all
the elements from the set.

Copy() method

Python set copy () method is used to copy the given input set.

Syntax:

Figure 3.5.4(b) Syntax of copy ()

65
Example 2: Write a program to copy all elements from a set to another set.

In above example 2, we are trying to copy all elements from set1 to set2 by set1.copy(), it will
copy all the elements from the set1 to set2.

Pop() method

Python Set pop () Method in python set is an inbuilt method which is used to removes a
random element from the set and returns the popped (removed) elements.

Syntax:

Figure 3.5.4(c) Syntax of pop ()

Example 3: Write a program to remove any random element from a set.

In above example 3, we are trying to remove any random element from set1 by set1.pop (),
it removed orange element from the set1.

Remove() method

Python Set remove () Method in python set is used to remove the specified element from the
given set. This method will raise an error if element does not exist in the set.

66
Syntax:

Figure 3.5.4(d) Syntax of remove ()

Example 4: Write a program to remove any specific element from a set.

In above example 4,we are trying to remove any specific element from set1 by
set1.remove(“mango”), it removed mango element from the set1 .

Discard() method

Python set discard () method is used to remove the specified item from the given input set. It
is different from the remove () method because the remove() method will give an error if the
specified item does not exist but this method will not.

Syntax:

Method Item to be
Name deleted

Figure 3.5.4(e) Syntax of discard ()

Example 5: Write a program to remove any specific element from a set.

67
In above example 5, we are trying to remove any specific element from set1 by
set1.discard(“mango”), it removed mango element from the set1.

Len() method

The set Len is one of the set method used to find the length of a set (total number of items)

Syntax:

Method Name of
Name set

Figure 3.5.4(f) Syntax of len()

Example 6: Write a program to count the elements of the set.

In above example 6, we are trying to find the number of elements from set1 by len(set1), it
returns the number of elements that is 3 from the set1 .

Practice Questions:

• Check if two lists have at-least one element common


• Find the Maximum and Minimum in a Set

3.5.5 Operators
Sometimes a necessity arises wherein we need to establish the relationship between two
sets. There comes the concept of set operations. If we have two sets (set1 and set2), we can
perform joint operations on both sets by either using an operator or calling a method
function.

Some of the set operations and respective method is shown in the table 3.5.5.

68
Table 3.5.5: Set Methods

Set Operation Description Operator Method

Union All unique elements in set1 and set2 | union()

Intersection Elements present in set1 and set2 & intersection()

Elements that are present in one


Difference - difference()
set, but not the other

Symmetric Elements present in one set or the


^ symmetric_difference()
Difference other, but not both

True if the two sets have no


Disjoint None isdisjoint()
elements in common

True if one set is a subset of the


Subset other (that is, all elements <= issubset()
of set2 are also in set1)

True if one set is a subset of the


Proper
other, but set2 and set1 cannot be < None
Subset
identical

True if one set is a superset of the


Superset other (that is, set1 contains all >= issuperset()
elements of set2)

True if one set is a superset of the


Proper
other, but set1 and set2 cannot be > None
Superset
identical

Some essential operations on set are:

1. Union:

69
In a class of 60 students, 35 said they loved Python, 30 said they loved Java. The teacher
wanted to know how many students loved Python and Java. So we will take the union of
Python and Java group sets to get the required solution.

Figure 3.5.5(a): Union operator | Example

Let two sets are set1 and set2; union operation fetches all the sets' elements. Figure
3.5.5(b,c) shown the examples of union operation and method on set1 and set2.

Figure 3.5.5(b): Union operator | on set1 and set2

Union method to join two sets

Output

Figure 3.5.5(c): Union () method on set1 and set2

70
2. Intersection:
In a class of 60 students, 35 said they loved Python, 30 said they loved Java. The teacher
wanted to know how many students loved both Python and Java. So we will take the
intersection of Python and Java group sets.

(Python & Java)

Python Java

Figure 3.5.5(d): Intersection operator & Example

Let, two sets are set1 and set2, intersection operation fetches all the common elements
in both set1 and set2. Figure 3.5.5(e,f) shown the example of intersection operation and
method.

Figure 3.5.5(e): Intersection operator & on set1 and set2

71
Figure 3.5.5(f): Intersection () method on set1 and set2

3. Set Difference:
In a class of 60 students, 35 said they loved Python, 30 said they loved Java.The teacher
wanted to know how many students loved Python but not Java (Python -Java) and how
many students loved Java but not Python (Java-Python), so we will take the set difference
of Python and Java group sets.

Figure 3.5.5(g): Set Difference - Example

Suppose you have two sets set1 and set2. The difference of set1 and set2 (set1 - set2) is
the set with all elements that are in set1 but not in set2. Consequently, (set2 - set1) is the
set with all the elements in set2 but not in set1.
To determine set differences in Python, we can use either the difference () function or the
- operator.

72
- operator to find difference among two sets

Output

Figure 3.5.5(e): Difference operator - on set1 and set2

Figure 3.5.5(e): Difference() method on set1 and set2

4. Symmetric Difference:

In a class of 60 students, 35 said they loved Python, 30 said they loved Java. The teacher
wanted to know how many students loved Python and Java but except the students who like
both Java and Python.

Figure 3.5.5(f): Symmetric Difference ^ Example

73
The symmetric difference of sets A and B is the set with all elements that are in A and B
except the elements that are common in both sets. It is determined using the Python's
symmetric_difference() method or the ^ operator.

^ operator to find symmetric


difference among two sets
Output

Figure 3.5.5(g): Symmetric Difference ^ operator on set1 and set2

Figure 3.5.5(h): Symmetric_difference method on set1 and set2

Practice Questions:

1. Write a Python program to check if a given set is superset of itself and superset of
another given set.
2. Write a Python program to find the elements in a given set that are not in another
set.

3.5.6 Loops

We cannot access items in a set by referring to an index, but we can loop through the set
items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

74
Figure 3.5.6(a): For loop on set

Practice Questions:

1. Write a Python program to check if a given value is present in a set or not.


2. Write a Python program to remove an item from a set using loop if it is present in
the set.

3.5.7 Frozen Set


A frozen set is a special category of the set which is unchangeable once created. Figure 3.4.7(a)
shows the creation of a frozen set.

Syntax:

Figure 3.5.7(a): Syntax for Frozen Set

Example 1: Write a program to create non empty and frozen set.

75
In above example 1, an non empty set is created using set () and frozenset is created using
frozenset(set1 ).

In Figure 3.5.7(b) shows adding the element in a set using add () method we got the attribute
error while adding an element in the frozen set.

Figure 3.5.7(b): Trying to add an element in Frozen set

Note: Like normal sets, frozenset can also perform different operations like copy,
difference, intersection, symmetric_difference, and union.

Practice Questions:

• What is the difference between a set and a frozenset?


• Why frozenset is required?
Example Exercise with Solution
Exercise: Write Python program to find common elements from three given lists using sets.
Solution:

76
3.6 Summary
There are four collection data types in the Python programming language. Table 3.6 shows
the difference between List, Tuple, Set, and Dictionary.

Table 3.6: Difference between List, Tuple, Set and Dictionary

List Tuple Set Dictionary


List is a collection Tuple is ordered and Set stores the Dictionary is a
of values that is unchangeable unique values as collection of key-value
ordered. collection of values data collection pairs
Represented by [ ] Represented by ( ) Represented by { } Represented by { }

Duplicate Duplicate elements Duplicate Duplicate keys not


elements allowed allowed elements not allowed, in dictionary
allowed values allowed
duplicate
Values can be of Values can be of any Values can be of Keys are immutable
any type type any type type, and value can be
of any type
Example: Example: Example: Example:
[1, 2, 3, 4] (1, 2, 3, 4) {1, 2, 3, 4} {1:1, 2:2, 3:3, 4:4}
List is mutable Tuple is immutable Set is mutable Dictionary is mutable

List is ordered Tuple is ordered Set is unordered Dictionary is insertion


ordered
Creating an empty Creating an empty Creating a set Creating an empty
list Tuple dictionary
s=set ()
l=list() t = tuple () d=dict( )

l = [] t=( ) d={}

77
References:

1. https://docs.python.org/3/library/math.html
2. Think Python: An Introduction to Software Design, Book by Allen B. Downey
3. Head First Python, 2nd Edition, by Paul Barry
4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna
Jablonski, Fletcher Heisler
5. http://javatpoint.com/
6. https://www.w3resource.com/
7. https://www.learnpython.org/en/Functions
8. https://www.datacamp.com/community/tutorials/functions-python-tutorial
9. https://data-flair.training/blogs/python-function/

78

You might also like