0% found this document useful (0 votes)
309 views102 pages

Unit-3 Python Complex Data Types

The document provides an overview of Python complex data types including sequences, strings, lists, tuples, sets and dictionaries. It discusses string operations like slicing, indexing, concatenation and formatting. Various programs are presented to demonstrate string manipulation through slicing, indexing, concatenation and formatting symbols. The key string methods and concepts covered are indexing, slicing, comparison operators, string formatting and built-in string functions.

Uploaded by

bawec59510
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
309 views102 pages

Unit-3 Python Complex Data Types

The document provides an overview of Python complex data types including sequences, strings, lists, tuples, sets and dictionaries. It discusses string operations like slicing, indexing, concatenation and formatting. Various programs are presented to demonstrate string manipulation through slicing, indexing, concatenation and formatting symbols. The key string methods and concepts covered are indexing, slicing, comparison operators, string formatting and built-in string functions.

Uploaded by

bawec59510
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 102

Unit-3 Python Complex data types:

Python Programming Unit-3 Prof. SHIV VEER SINGH 1


• Python Basic Data Structures • Slicing
• Sequence • Built-in string methods and
• Packing and Unpacking function
Sequences • Regular expressions
• Mutable Sequences • Lists
• Strings • Tuples
• Basic operations • Sets and Dictionaries with built-in
• Comparing strings methods
• string formatting • List Comprehension
• Looping in basic data structures

Python Programming Unit-3 Prof. SHIV VEER SINGH Unit IV 2


Standard Data types (CO3)

Data Types Keyword


Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set
Boolean Types bool
Binary Types bytes
Python Programming Unit-3 Prof. SHIV VEER SINGH 3
STRINGS

Python Programming Unit-3 Prof. SHIV VEER SINGH 4


Introduction to String [CO3]

In Python, Strings are arrays of bytes representing Unicode


characters.

However, Python does not have a character data type, a single


character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.

Python Programming Unit-3 Prof. SHIV VEER SINGH 5


Basic operations [CO3]
Traversing:
A string can be traversed by accessing character(s) from one index to another.
Concatenating:
Concatenate means joining two strings. We use + operator to concatenate two
given strings.
Appending:
Append means add something to the end of string. We use + = operator to add one
string at the end of another string.
Multiplying:
Means repeating a string n number of times
Python Programming Unit-3 Prof. SHIV VEER SINGH 6
Program to traverse a string using indexing [CO3]
msg=“Hello!” index=0;
for i in msg:
print(“msg[“, index,”]=“, i) index+=1
Output: msg[0]=H
msg[1]=e
msg[2]=l
msg[3]=l
msg[4]=o
msg[5]=!
Python Programming Unit-3 Prof. SHIV VEER SINGH 7
Program to concatenate two string using + operator [CO3]

str1=“Hello!”
str2=“world”
str3=str1+str2
print(“Concatenated string is :”, str3)

Output:
Concatenated string is : Hello! world

Python Programming Unit-3 Prof. SHIV VEER SINGH 8


Program to append a string using + operator [CO3]
str=“Hello!”
Name=input(“\nEnter your name:”) str+=name
str+= “.Welcome to python.”
print(str)

Output:
Enter your name: SHIV VEER
Hello! SHIV VEER . Welcome to python.
Python Programming Unit-3 Prof. SHIV VEER SINGH 9
Program to repeat a string using * operator [CO3]

str=“SHIV!” print(str * 3)

Output:
SHIV! SHIV! SHIV!

Python Programming Unit-3 Prof. SHIV VEER SINGH 10


String formatting operator [CO3]
String formatting operator is one of the exciting features of python. The
% operator takes a format string on the left (%d, %s etc) and
corresponding value in a tuple on the right.

The format operator % allows users to construct strings, replacing parts


of the strings with the data stored in variables.
Syntax:
“<FORMAT>”%(<VALUES>)

Python Programming Unit-3 Prof. SHIV VEER SINGH 11


Program to use format sequences [CO3]
name =“Ojaswa Rajput”
age=14
print(“Name = %s and age = %d” %(name, age))
print(“Name = %s and age = %d” %(“Adhya Rajput”, 11))

Output:
Name= Ojaswa Rajput and age = 14 Name = Adhya Rajput and age = 11

Python Programming Unit-3 Prof. SHIV VEER SINGH 12


Formatting symbols [CO3]
Operator Purpose
%c Character
%d or %i Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal Integer
%e or %E Exponential Notation
%f Floating point number
%g or %G Short numbers in floating point or
exponential notation
Python Programming Unit-3 Prof. SHIV VEER SINGH 13
Indexing [CO3]
• Individual characters in a string are accessed using the subscript ([])
operator. The expression in bracket is called index.
• The index specifies a member of an ordered set and here it specifies the character we
want to access from the given set of characters in the string.
• the first character has the position 0 and last character has n-1, where n is number of
characters
If you try to exceed the bounds (below 0 or above n-1) an error is raised Example:
Get the character at position 1
a = "Hello, World!"
print(a[1])
Output: e
Python Programming Unit-3 Prof. SHIV VEER SINGH 14
Slicing [CO3]

A substring of a string is called slice. The slice operation is used to refer to


sub-parts of strings.
We use [] operator also called slicing operator to take subset of a string from
original string.

P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Fig: Indices in a string
Python Programming Unit-3 Prof. SHIV VEER SINGH 15
slicing [CO3]
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a
part of the string.
Example
Get the characters from position 2 to position 5 (not included):
S=“Python!”
print(S[1:4])
Output:
yth
Python Programming Unit-3 Prof. SHIV VEER SINGH 16
Program to demonstrate slicing operation [CO3]
str = “PYTHON”
print(“str [1:5] = ”, str[1:5])
print(“str [:6] = ”, str[:6]) #defaults to start of string
print(“str [1:] = ”, str[1:]) #defaults to end of string print(“str [:] = ”,
str[:]) #defaults to entire string
print(“str [1:20] =”, str[1:20]) #truncates to length of the string
Output:
str [1:5] = YTHO str [:6]
= PYTHON str [1:] =
YTHON str[ : ] =
PYTHON str [1:20] =
YTHON

Python Programming Unit-3 Prof. SHIV VEER SINGH 17


Slice using Negative Indexing [CO3]
Use negative indexes to start the slice from the end of the
string:
Example
Get the characters from position 5 to position 1, starting the count
from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
Output:
orl

Python Programming Unit-3 Prof. SHIV VEER SINGH 18


Program to demonstrate slicing operation [CO3]
str = “PYTHON”
print(“str [-1] = “, str[-1])
print(“str [-6] = “, str[-6])
print(“str [-2:] = “, str[-2:])
print(“str [:-2] = “, str[:-2])
print(“str [-5:-2] = “, str[-5:-2])
Output:
str [-1] = N
str [-6] = P
str [-2:] = ON
str[ : -2] = PYTH
str [-5:-2] = YTH

Python Programming Unit-3 Prof. SHIV VEER SINGH 19


Comparing strings [CO3]
Operator Description Example
== If two strings are equal, it returns true >>> “ABC” == “ABC”
True
!= If two strings are not equal, it returns true >>> “AbC” != “ABC”
True
> If first string is greater than the second, it >>> “aBC” > “ABC”
returns true True
< If first string is smaller than the second, it >>> “ABC” < “aBC”
returns true True
>= If first string is greater than or equal to the >>> “aBC” >= “ABC”
second, it returns true True
<= If first string is smaller than or equal >>> “ABC” <= “aBC”
to True

Python Programming Unit-3 Prof. SHIV VEER SINGH 20


the second, it returns true
Escape Character [CO3]

• An escape character is a backslash \ followed by the character you want to insert.


• An example of an illegal character is a double quote inside a string that is
surrounded by double quotes:
Example
txt = “SHIV asks, \“How are you?\” ”
print(txt)
Output:
SHIV asks, “How are you? ”

Python Programming Unit-3 Prof. SHIV VEER SINGH 21


Escape characters [CO3]
Escape character Description

\' Single Quote


\’’ Double Quote
\\ Backslash
\n New Line
\t Tab

\b Backspace

Python Programming Unit-3 Prof. SHIV VEER SINGH 22


STRING METHODS [CO3]
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a
string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the
position of where it was found
format() Formats specified values in a string
Python Programming Unit-3 Prof. SHIV VEER SINGH 23
STRING METHODS [CO3]
Method Description
index() Searches the string for a specified value and returns the position of
where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
upper() Converts a string into upper case
Python Programming Unit-3 Prof. SHIV VEER SINGH 24
STRING METHODS [CO3]
Method Description
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
rjust() Returns a right justified version of the string
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
strip() Returns a trimmed version of the string
Python Programming Unit-3 Prof. SHIV VEER SINGH 25
Python data structure

Python data structure

Python Programming Unit-3 Prof. SHIV VEER SINGH 26


Content
• Sequence
• Unpacking Sequences
• Mutable Sequences
• Lists
• List Comprehension
• Looping in lists
• Tuples
• Sets
• Dictionaries

Python Programming Unit-3 Prof. SHIV VEER SINGH 27


Sequence [CO3]
• In Python, a sequence is the ordered collection of similar or different
data types. It is a generic term for ordered set.
• In sequence, each element has a specific index that starts from 0 and
is automatically incremented for next element in the sequence.
• Sequence Sequences allow storing multiple values in an organized
and efficient fashion. There are several sequence types in Python –
 String
 List
 Tuple
Python Programming Unit-3 Prof. SHIV VEER SINGH 28
Types of Sequence [CO3]

• Sequence types: strings, Unicode strings, lists, tuples, and range objects.
• String's literals are written in single or double quotes: 'xyzzy', "frobozz".
• Lists are constructed with square brackets, separating items with commas:
[a, b, c].
• Tuples are constructed by the comma operator (not within square brackets),
with or without enclosing parentheses, but an empty tuple must have the
enclosing parentheses, e.g., a, b, c or (). A single item tuple must have a trailing
comma, e.g., (d,).
• range objects are used to create a sequence of numeric values.

Python Programming Unit-3 Prof. SHIV VEER SINGH 29


Packing in Python

Packing Sequences [CO3]

• Packing is a technique in python with which we put several values into a


single iterator. If we talk of packing in literal terms, Just like we pack
certain items into a box in the real world, In python we pack certain
variables in a single iterable.

Python Programming Unit-3 Prof. SHIV VEER SINGH 30


How to perform packing in Python ?
• We can perform packing by using simple syntax for declaration of iterables like list
or tuples or we can use asterisk operator * for packing. The
* operator is used as an operator for unpacking the iterables into variables but it
allows us to pack a number of variables into a single variable.
• For example, suppose we have three variables num1, num2,num3. We can
pack them into a tuple as follows.
num1=1
num2=2
num3=3
myTuple=(num1,num2,num3)
Python Programming Unit-3 Prof. SHIV VEER SINGH 31
How to perform packing in Python ?

• Or we can pack them into a list as follows.


num1=1
num2=2
num3=3
myList=[num1,num2,num3]

Python Programming Unit-3 Prof. SHIV VEER SINGH 32


How to perform packing in Python ?

Alternatively, we can use * operator to pack the numbers together as


follows.
num1=1
num2=2
num3=3
*num,=num1,num2,num3

Python Programming Unit-3 Prof. SHIV VEER SINGH 33


How to perform packing in Python ?

• We have used a comma “,” after the *num because the left hand side of the
assignment operation must be a tuple or list otherwise error will be encountered.
• In the left side, when we use * operator, we can also have other variables which can
be assigned the values. For example, we can pack two numbers into a variable and a
third number can be assigned to another variable as follows.
num1=1
num2=2
num3=3
*num,myNum=num1,num2,num3

Python Programming Unit-3 Prof. SHIV VEER SINGH 34


How to perform packing in Python ?

In the above example, we have to remember that myNum is a mandatory


variable and it must be assigned some value whereas *num can be assigned
no value. Here, num3 will be assigned to myNum and num1 and num2 will
be packed in the list num.

Python Programming Unit-3 Prof. SHIV VEER SINGH 35


Unpacking Sequences [CO3]

• Let we have a function that receives four arguments. Also, we


have a list of size 4 that has all arguments for the function. When
we make call to this function and simply pass list to the function,
the call doesn’t work.

Python Programming Unit-3 Prof. SHIV VEER SINGH 36


Python program to understand need of unpacking [CO3]
# A sample function that takes 4 arguments and prints
them.
def func(a, b, c, d):
print(a, b, c, d)

#driver Code
my_list = [1, 2, 3, 4]
func(my_list) # This doesn't work
Python Programming Unit-3 Prof. SHIV VEER SINGH 37
Python program to understand need of unpacking [CO3]
Unpacking
We can use * to unpack the list so that all elements of it can
be passed as different parameters.
# A sample function that takes 4 arguments and prints them
def fun(a, b, c, d):
print(a, b, c, d)
# Driver Code Output
my_list = [1, 2, 3, 4] 1234
fun(*my_list) # Unpacking list into four arguments
Python Programming Unit-3 Prof. SHIV VEER SINGH 38
Mutable Sequences [CO3]

• Mutable Sequences:
Sequence that can change their state or contents are called mutable
sequence.
These are of type list, dict, set . Custom classes are generally
mutable.

Python Programming Unit-3 Prof. SHIV VEER SINGH 39


Mutable Sequences [CO3]

# Python code to test that lists are mutable


color = ["red", "blue", "green"]
print(color) Output
['red', 'blue', 'green']
color[0] = "pink"
color[-1] = "orange"
print(color) Output
['pink', 'blue', 'orange']

Python Programming Unit-3 Prof. SHIV VEER SINGH 40


Lists [CO3]

• Lists are like arrays, declared in other languages.


• A single list may contain data types such as Integers, Strings or
Objects.
• The elements in a list are indexed according to a definite
sequence.
• indexing of a list is done with 0 being the first index. It is
represented by list class.
Python Programming Unit-3 Prof. SHIV VEER SINGH 41
Python program to understand Creation of List [CO3]
# Creating a List Output
List = [ ] []
print(List)

# Creating a list of strings


List = ['Python Programming', 'Python'] Output
print(List) ['Python Programming', 'Python']

# Creating a Multi-Dimensional List


List = [['Python', 'For'], ['Beginners']]
Output
print(List)
[['Python', 'For'], ['Beginners']]
Python Programming Unit-3 Prof. SHIV VEER SINGH 42
Python program to Access elements from the List [CO3]
Use the index operator [ ] to access an item in a list. In Python, negative sequence indexes
represent positions from the end of the array. Instead of having to compute the offset as in
List[len(List)-3], it is enough to just write List[-3].

List = [1, 2, 3, 4, 5, 6]
Output
# accessing a element
print(List[0]) 1
3
print(List[2]) Output
# Negative indexing
6
print(List[-1]) # print the last element of list 4
print(List[-3]) # print the third last element of list
Python Programming Unit-3 Prof. SHIV VEER SINGH 43
List methods [CO3]
Method Description Syntax Example output

append() Appends an element to list.append(obj) list=[1,2,3,4,5] [1,2,3,4,5,8]


the list list.append(8)
print(list)

count() count number of times list.count(obj) list=[1,2,3,4,5] 1


element appears in the print(list.count(3))
list

index() Returns lowest index of list.index(obj) list=[1,2,3,4,5] 2


element in list print(list.index(3))

Python Programming Unit-3 Prof. SHIV VEER SINGH 44


List methods [CO3]
Method Description Syntax Example output

insert() Insert object at list.insert(index,obj) list=[1,2,3,4,5] [1,2,3,10,4,5]


the specified list.insert(3, 10)
index in the list print(list)

pop() Removes element list.pop(index) list=[1,2,3,4,5] 5


at specified index print(list.pop()) [1,2,3,4]
from list(by default print(list)
last)

Python Programming Unit-3 Prof. SHIV VEER SINGH 45


List methods[CO3]
Method Description Syntax Example output

remove() removes the list.remove(obj) list=[1,2,3,4,5] [2,3,4,5]


elements in the list.remove(1)
list print(list)

reverse() reverse the list.reverse() list=[1,2,3,4,5] [5, 4, 3, 2, 1]


elements in the list.reverse()
list print(list)

Python Programming Unit-3 Prof. SHIV VEER SINGH 46


List methods[CO3]
Method Description Syntax Example output

sort() sorts the elements in list.sort() list=[5,2,4,1,3] [1,2,3,4,5]


the list list.sort()
print(list)

extend() adds the elements list1.extend(list2) list1=[1,2,3,4,5] [1,2,3,4,5,6,7]


in a list to the end list2=[6,7]
of another list list1.extend(list2)
print(list1)

Python Programming Unit-3 Prof. SHIV VEER SINGH 47


Python program to demonstrate Addition of elements in a List
Using append(), insert() and extend() [CO3]
# Creating a List
List = []
# Using append()
List.append(5) Output
List.append(6)
print(List) [5, 6]

# Using insert()
List.insert(3, 12) Output
List.insert(0, 'Begin')
print(List) ['Begin', 5, 6, 12]

# Using extend() Output


List.extend([18, 'keep', 'smiling'])
print(List) ['Begin', 5, 6, 12, 18, 'Keep', 'smiling']
Program to demonstrate removal of elements from a List
Using remove() and pop() [CO3]

# Creating a List
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# using Remove() method
List.remove(5)
List.remove(6)
Output
print(List) [1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

# using pop() Output


List.pop()
[1, 2, 3, 4, 7, 8, 9, 10, 11]
print(List)
List Comprehension [CO3]

• Python supports computed lists called list comprehensions having


following syntax:
• List =[expression for variable in sequence]
• Where the expression is evaluated once, for every item in the sequence.
• List comprehension help programmers to create list in a concise way.
• This is mainly beneficial to make new lists where each element is obtained
by applying some operations to each member of another sequence or iterable.
• List comprehension is also used to create a subsequence of those elements
that satisfy a certain condition.

Python Programming Unit-3 Prof. SHIV VEER SINGH 50


Program to make a list of cubes [CO3]

cubes = [ ]
for i in range (11):
cubes.append(i**3)
print(“cubes of numbers from 1-10: ”, cubes)

Output:
cubes of numbers from 1-10 :
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Python Programming Unit-3 Prof. SHIV VEER SINGH 51
Program to make a list of cubes using iterable [CO3]

Iterable:
An iterable is an object that can be used repeatedly in subsequent loop
statements, e.g. for loop

Rewriting program to make list of cubes using iterable:


>> cubes = [i**3 for i in range(11)]
>> print(cubes)
Output:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Python Programming Unit-3 Prof. SHIV VEER SINGH 52
Program to combine and print elements of two list [CO3]

print([(x, y) for x in [10, 20, 30] for y in [30, 10, 40] if x!=y])

Output:
[(10, 30), (10, 40), (20, 30), (20, 10), (20, 40), (30, 10), (30, 40)]

Python Programming Unit-3 Prof. SHIV VEER SINGH 53


Looping in lists
#using for loop [CO3]

There are multiple ways to iterate over a list in Python. Output


Method #1: Using For loop
1
2
3
list = [1, 2, 3, 4, 5]
4
for i in list: 5
print(i)

Python Programming Unit-3 Prof. SHIV VEER SINGH 54


Looping in lists
Method #2: For loop and range() [CO3]

Using traditional for loop that iterates from number x to


number y.
# iterating over a list Output
list = [1, 2, 3, 4, 5] 1
length = len(list) 2
for i in range(length): 3
print(list[i]) 4
5
Looping in lists
Method #3: Using while loop [CO3]

list = [1, 2, 3, 4, 5]
length = len (list)
i=0
while i < length:
print(list[i]) Output
i += 1 1
2
3
4
5
Looping in lists
Method #4: Using list comprehension [CO3]

list = [1, 2, 3, 4, 5]
[print(i) for i in list]
Output
1
2
3
4
5
Looping in lists
Method #5: Using enumerate [CO3]

list = [11, 12, 13, 14, 15]


for i, val in enumerate(list):
Output
print (i, ",",val)
0 , 11
1 , 12
2 , 13
3 , 14
Python Enumerate() is a buit-in function available with the 4 , 15
Python library. It takes the given input as a collection or tuples
and returns it as an enumerate object. The Python Enumerate()
command adds a counter to each item of the iterable object and
returns an enumerate object as an output string.
Program to find sum and mean of elements in a list [CO3]

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


sum=0
for i in list:
sum+= i
print (”sum of elements in list=”, sum) length=len(list)
print ( ”mean of elements in list=”, sum/length)
Output
sum of elements in list= 55
mean of elements in list= 5.5
Python Programming Unit-3 Prof. SHIV VEER SINGH 59
Tuples [CO3]

Tuple
• A tuple is a collection which is ordered and
unchangeable. In Python tuples are written with round
brackets.
• A tuple is an immutable sequence of Python objects.

Python Programming Unit-3 Prof. SHIV VEER SINGH 60


Tuples vs lists [CO3]

• Tuples are sequences, just like lists.


• The differences between tuples and lists are, the tuples cannot be
changed unlike lists.
• Tuples use parentheses, whereas lists use square brackets.
• Creating a tuple is as simple as putting different comma-
separated values.

Python Programming Unit-3 Prof. SHIV VEER SINGH 61


Creating Tuple [CO3]
For creating a tuple, one need to just put the different comma separated
values within a parentheses.

Tup = (val1, val2, …….) where val can be integer, floating number, character or a string.

Example
tup = ("SHIV", "VEER", "SINGH")

print(tup)
Output:
("SHIV", "VEER", "SINGH")
Python Programming Unit-3 Prof. SHIV VEER SINGH 62
Access Tuple Items [CO3]
You can access tuple items by referring to the index number, inside square brackets:
Example
print the second item in the tuple:
tup1 = ("SHIV", "VEER", "SINGH")
tup2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Output
print(tup1[0])
SHIV
print(tup2[3:6])
(4, 5, 6)
print(tup2[:4]) (1, 2, 3, 4)
print(tup2[4:]) (5, 6, 7, 8, 9, 10)
print(tup2[:]) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(tup2[-1]) // beginning from end 10
print(tup2[-3:-1]) (8, 9)

Python Programming Unit-3 Prof. SHIV VEER SINGH 63


Change Tuple Values [CO3]
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list
back into a tuple.
Example: Convert the tuple into a list to be able to change it:
x = ("SHIV", "VEER", "SINGH")
y = list(x)
y[1] = "Rajput"
x = tuple(y)
print(x)
Output:
("SHIV", “Rajput", "SINGH")
Python Programming Unit-3 Prof. SHIV VEER SINGH 64
Loop Through a Tuple [CO3]
You can loop through the tuple items by using a for loop.

Example: Iterate through the items and print the values:


thistuple = ("SHIV", "VEER", "SINGH")

for x in thistuple:
print(x)

Output:
SHIV
VEER
SINGH
Python Programming Unit-3 Prof. SHIV VEER SINGH 65
Tuple Assignment [CO3]
It allows tuple of variables on left hand side of the assignment operator to be
assigned values from a tuple on the right hand side of the assignment operator.
Each value is assigned to its respective variable.
Example:
(a, b, c)= (1, 2, 3)
print (a, b, c) Output
Tup1=(100, 200, 300) 123
(a, b, c)= Tup1 100 200 300
print (a, b, c) 7 6.333333 3
(a, b, c) = (3 + 4, 7 / 3 + 4, 9 % 6)
print (a, b, c)

Python Programming Unit-3 Prof. SHIV VEER SINGH 66


Check if Item Exists In Tuples [CO3]
To determine if a specified item is present in a tuple use the in
keyword:

Example: Check if "SHIV" is present in the tuple:

thistuple = ("SHIV", "VEER", "SINGH")


if "SHIV" in thistuple:
print("Yes, SHIV' is in the thistuple")

output:
Yes, 'SHIV' is in the thistuple
Python Programming Unit-3 Prof. SHIV VEER SINGH 67
Tuple Length [CO3]

To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("SHIV", "VEER", "SINGH")
print(len(thistuple))
3
Python Programming Unit-3 Prof. SHIV VEER SINGH 68
Tuple Methods [CO3]
Python has two built-in methods that you can use on tuples.
count(): returns the number of times a specified value occurs in a tuple
Tup=(1,2,3,3,5,6,3,8) Output
print(Tup.count(3)) 3
index(): Searches the tuple for a specified value and returns the position
of where it was found
Output
Tup=(1,2,3,4,5,6,7,8)
3
print(Tup.index(4))
Python Programming Unit-3 Prof. SHIV VEER SINGH 69
Join Two Tuples [CO3]
To join two or more tuples, you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output ('a', 'b', 'c', 1, 2, 3)

Python Programming Unit-3 Prof. SHIV VEER SINGH 70


Remove Items in tuple [CO3]
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
Example: The del keyword can delete the tuple completely:

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


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
Python Programming Unit-3 Prof. SHIV VEER SINGH 71
Tuples returning multiple values [CO3]
A function can return only a single value. But when we need to return
more than one value from a function, we group them as tuple and return
def max_min(*vals):
x = max(vals)
y = min(vals)
return (x, y)
a, b = max_min(23,45,78,12,34,91) Output
print(a, b) 91 12

Python Programming Unit-3 Prof. SHIV VEER SINGH 72


Nesting of Tuples [CO3]
Process of defining a tuple inside another tuple is called Nesting of tuple.
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'programming')
tuple3 = (tuple1, tuple2) print(tuple3)
Output :
((0, 1, 2, 3), ('python', 'programming'))

Python Programming Unit-3 Prof. SHIV VEER SINGH 73


SETS

SETS

Python Programming Unit-3 Prof. SHIV VEER SINGH 74


SETS [CO3]
Definition:
A set is a collection which is unordered and unindexed. In Python
sets are written with curly brackets.
A set is mutable i.e., we can easily add or remove items from a set
Set are same as list but with a difference that sets are list with no
duplicate entries.

Python Programming Unit-3 Prof. SHIV VEER SINGH 75


Creating a SET [CO3]

A set is created by placing all the elements inside curly brackets.


Example
Create a Set:
thisset = {"SHIV", "VEER", "SINGH"}
print(thisset)
{SHIV', VEER', SINGH'}

Python Programming Unit-3 Prof. SHIV VEER SINGH 76


Access Items in a SET [CO3]
• Items in a set can’t be accessed by referring to an index, since sets
are unordered the items has no index.
• Using for loop the items in the set can be iterated.
• Example
thisset = {"SHIV", "VEER", "SINGH”} Output
for x in thisset:
SHIV
print(x)
VEER
SINGH
Python Programming Unit-3 Prof. SHIV VEER SINGH 77
SETS [CO3]

Change Items
Once a set is created, items of the set can’t be changed but
a new item can be added.

Python Programming Unit-3 Prof. SHIV VEER SINGH 78


Add Items to a SET [CO3]
• To add one item to a set, use the add() method.
• To add more than one item to a set use the update() method.
• Example
Add an item to a set, using the add() method:
thisset = {"SHIV", "VEER", "SINGH”}
thisset.add("RAJPUT")
print(thisset)
Output:
{"SHIV", "VEER", "SINGH”, “RAJPUT”}

Python Programming Unit-3 Prof. SHIV VEER SINGH 79


Add Multiple Items to a SET [CO3]
Example
Add multiple items to a set, using the update() method:
thisset = {"SHIV", "VEER", "SINGH”}
thisset.update(["PROF.", "CSE", "IOT"])
print(thisset)
Output:
{"SHIV", "VEER", "SINGH”, "PROF.", "CSE", "IOT"]) }
Python Programming Unit-3 Prof. SHIV VEER SINGH 80
Get the Length of a Set [CO3]
To determine how many items a set has, use the len()
method.
Example
Get the number of items in a set:
thisset = {"SHIV", "VEER", "SINGH”, "PROF.", "CSE", "IOT"]) }
print(len(thisset))
Output: 6

Python Programming Unit-3 Prof. SHIV VEER SINGH 81


Remove Item from a Set [CO3]
To remove an item in a set, use the remove(), or the discard()
method.
Example: Remove "banana" by using the remove() method:
thisset = {"SHIV", "VEER", "SINGH”, "PROF.", "CSE", "IOT"]) }
thisset.remove("IOT") print(thisset)
# thisset.discard("IOT")
Output:
{"SHIV", "VEER", "SINGH”, "PROF.", "CSE", }

Note: If the item to remove does not exist, remove() will raise an error while
discard does not give error
Python Programming Unit-3 Prof. SHIV VEER SINGH 82
Join Two Sets [CO3]
• You can use the union() method that returns a new set containing all items
from both sets, or
• the update() method that inserts all the items from one set into
another:
Example
The union() method returns a new set with all items from both sets: set1 =
{"a", "b" , "c"}
set2 = {1, 2, 3} Output
set3 = set1.union(set2)
print(set3) {'c', 'b', 2, 3, 1, 'a'}

Python Programming Unit-3 Prof. SHIV VEER SINGH 83


Join Two Sets [CO3]
The update() method inserts the items in set2 into set1: set1 =
{"a", "b" , "c"}
Output
set2 = {1, 2, 3}
set1.update(set2) {'c', 3, 'a', 'b', 1, 2}
print(set1)
Note: Both union() and update() will exclude any duplicate
items.
Python Programming Unit-3 Prof. SHIV VEER SINGH 84
SETS [CO3]
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another,
specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have an intersection or not

Python Programming Unit-3 Prof. SHIV VEER SINGH 85


SETS [CO3]
Method Description
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and
another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
Python Programming Unit-3 Prof. SHIV VEER SINGH 86
Dictionaries

Dictionaries

Python Programming Unit-3 Prof. SHIV VEER SINGH 87


Dictionaries [CO3]
Dictionary
• A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets, and
they have keys and values.
• Each key is separated from its value by a colon (:) and consecutive
items are separated by commas.
• Entire items in dictionary are enclosed in curly brackets ({}).

Python Programming Unit-3 Prof. SHIV VEER SINGH 88


Dictionaries [CO3]

Syntax:
dictionary_name = {key1:value1, key2:value2, key3:value3}

Value of key can be of any type


Dictionary keys are case sensitive. Two keys with same name but
in different case are not same in Python.

Python Programming Unit-3 Prof. SHIV VEER SINGH 89


Dictionaries [CO3]
• Creating an empty dictionary Output
dict = {} {}
print(dict)
• Create and print a dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }
print(thisdict)
Output
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Python Programming Unit-3 Prof. SHIV VEER SINGH 90


Accessing Items in Dictionaries [CO3]
You can access the items of a dictionary by referring to its key name, inside square
brackets:
Example: Get the value of the "model" key:

thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Output:
Mustang
Python Programming Unit-3 Prof. SHIV VEER SINGH 91
Accessing Items in Dictionaries [CO3]

There is also a method called get() that will give you the same result:
Example: Get the value of the "model" key:
thisdict ={"brand": "Ford", "model": "Mustang", "year": 1964 }
x = thisdict.get("model")
print(x)

Mustang

Python Programming Unit-3 Prof. SHIV VEER SINGH 92


Modifying an item in Dictionary [CO3]
• The value of a specific item can be changed by referring to its key name:
Example
Change the "year" to 2018:

thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }


thisdict["year"] = 2018
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Python Programming Unit-3 Prof. SHIV VEER SINGH 93
Loop Through a Dictionary [CO3]
• When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Example:
Print all key names in the dictionary, one by one:
thisdict ={ "brand": "Ford", "model": "Mustang", "year": 1964}

for x in thisdict: brand


print(x) Output mode
l year
Python Programming Unit-3 Prof. SHIV VEER SINGH 94
Check if Key Exists [CO3]
• To determine if a specified key is present in a dictionary use the in
keyword.
• Check if "model" is present in the dictionary:

thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }


if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Output:
Yes, 'model' is one of the keys in the thisdict dictionary
Python Programming Unit-3 Prof. SHIV VEER SINGH 95
Adding Items [CO3]
• Adding an item to the dictionary is done by using a new index
key and assigning a value to it:
• Example
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964 }
thisdict["color"] = "red"
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Python Programming Unit-3 Prof. SHIV VEER SINGH 96
Removing Items from Dictionaries [CO3]
Method1
The pop() method removes the item with the specified key name:

thisdict = {"brand": "Ford","model": "Mustang","year": 1964}


thisdict.pop("model")
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
Python Programming Unit-3 Prof. SHIV VEER SINGH 97
Removing Items from Dictionaries [CO3]

Method 2
The del keyword removes the item with the specified key name:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
del thisdict["model"]
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
Python Programming Unit-3 Prof. SHIV VEER SINGH 98
Removing Items from Dictionaries [CO3]
Method 3
The del keyword can also delete the dictionary completely:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
del thisdict
print(thisdict)
Output:
#print statement will cause an error because "thisdict" no longer exists.

Python Programming Unit-3 Prof. SHIV VEER SINGH 99


Removing Items from Dictionaries [CO3]
Method 4
The clear() method empties the dictionary:

thisdict = {"brand": "Ford","model": "Mustang","year": 1964 }


thisdict.clear()
print(thisdict)
Output:
{}
Python Programming Unit-3 Prof. SHIV VEER SINGH 100
Nested Dictionaries [CO3]
Example: Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : { "name" : }
"Emil", "year" : print(myfamily) A dictionary can
2004 also contain many
},
"child2" : { dictionaries, this is
"name" : "Tobias", called nested
"year" : 2007 dictionaries.
},
"child3" : { "name" : Output
"Linus", "year" :
2011 {'child1': {'name': 'Emil', 'year': 2004}, 'child2':
} {'name':
'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}

Python Programming Unit-3 Prof. SHIV VEER SINGH 101


Dictionary method [CO3]
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value

update() Updates the dictionary with the specified key-value pairs


values() Returns a list of all the values in the dictionary
Python Programming Unit-3 Prof. SHIV VEER SINGH

You might also like