0% found this document useful (0 votes)
30 views47 pages

Unit 3-5

The document provides an overview of Python complex data types, specifically focusing on strings, lists, and tuples. It covers methods for creating, manipulating, and utilizing these data structures, including various built-in functions and operations. The content is structured to facilitate understanding and application in Python programming.

Uploaded by

materialstudy072
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)
30 views47 pages

Unit 3-5

The document provides an overview of Python complex data types, specifically focusing on strings, lists, and tuples. It covers methods for creating, manipulating, and utilizing these data structures, including various built-in functions and operations. The content is structured to facilitate understanding and application in Python programming.

Uploaded by

materialstudy072
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/ 47

Department of Computer Science

IMS Engineering College

UNIT – 3
PYTHON COMPLEX DATA TYPES

Course Outcome: Determine the methods to create and manipulate python programs by
utilizing the data structures like lists, dictionaries, tuples and sets.

Topic Coverage
Using string data type and string operations, Defining list and list slicing, Use of Tuple data
type. String, List and Dictionary, Manipulating building blocks of python programs, string
manipulation methods, List manipulation. Dictionary manipulation, Programming using string,
list and dictionary in-built functions. Python Functions, Organizing Python codes using
functions.

PYTHON STRING
A string is a sequence of characters. A string may be specified by placing the characters of the
sequence within quotes (single, double, triple). Triple quotes are generally used for strings that
spans multiple lines.

Output will be:

Output will be:

Calculating Length of String


We can calculate length of the string by using len( ) function.

Python Programming 1 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

Accessing individual character of the string using index


• Indices start with 0 (index for accessing the first character from the left) and end with
one less than the
• The length of the string (index for accessing the last character).
• The index is specified within the square brackets.
• To access the elements of the string from right end, python provides negative indices.

Example:

Output will be:

Example: Accessing index out of range

Output will be:

Python Programming 2 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Immutable Strings
• A component of string cannot be altered.
• An attempt to do so would lead to an error.
Example:

Output will be:

String Concatenation and Multiplication Operators

Output will be:

Example: Using string multiplication operator, we can print the pattern.

Output will be:

String Max and Min Function

Python Programming 3 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

String Slicing
• Slicing is done to retrieve a substring.
• This can be done by specifying an index range.
• For example, to access the substring of character sequence having indices from start to
end-1, we need to specify the range from start to end.
• If the value of start or end is not specified, Python assumes 0 as the default value of
start and length of the string as the default value of end.
Example:

Output will be:

Python Programming 4 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

Note: message[:n] + message[n:] always print message, irrespective of the value of n being
positive, negative or even out of range.

Apart from extracting a consecutive subsequence of characters from a string, Python also allow
to extract a subsequence of the form [start:end:inc].
Example:

Output will be:

String Membership Operator

Python Programming 5 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example:

Output will be:

Output will be:

String in-built Functions

• s.count(str1) Count number of times string str1 occurs in the string s.


Example:

Output will be:

• s.find(str1) Returns index of first occurrence of the string str1 in string s. Returns -1 if
str1 is not present in string s.
Example:

Output will be:

Python Programming 6 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• s.rfind(str1) Returns index of last occurrence of the string str1 in string s. Returns -1
if str1 is not present in string s.
Example:

Output will be:

• s.capitalize( ) Returns a string that has first letter of string s in uppercase.


Example:

Output will be:

• s.title( ) Returns a string that has first letter of every word of string s in uppercase.
Example:

Output will be:

• s.lower() Converts all letters of the string s into lowercase.


Example:

Output will be:

• s.upper() Converts all letters of the string s into uppercase.


Example:

Python Programming 7 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

• s.swapcase() Converts all uppercase letters of the string s into lowercase and vice versa.
Example:

Output will be:

• s.islower() Returns True if all alphabets in string s are in lowercase, else returns False.
Example:

Output will be:

• s.isupper() Returns True if all alphabets in string s are in uppercase, else returns False.
Example:

Output will be:

• s.istitle() Returns True if string s is in title case, else return False.


Example:

Output will be:

Python Programming 8 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• s.replace(str1, str2) or s.replace(str1, str2, n) Replace every occurrence of str1 by


str2 OR replace n number of occurrences of str1 by str2.
Example:

Output will be:

• s.strip() Returns a string that has whitespaces in s removed from the beginning and the
end.
Example:

Output will be:

• s.lstrip() Returns a string that has whitespaces in s removed from the beginning.
Example:

Output will be:

• s.rstrip() Returns a string that has whitespaces in s removed from the end.
Example:

Python Programming 9 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

• s.split(delimiter) Returns a list formed by splitting the string s into substrings. The
delimiter is used to mark the split points.
Example:

Output will be:

• s.partition(delimiter) Partitions the string s into 3 parts based on delimiter and returns
a tuple comprising the string before delimiter, delimiter itself and the string after
delimiter.
Example:

Output will be:

It is mandatory to specify delimiter in the partition( ) function. If not specified, it will


result in TypeError.
Example:

Output will be:

Python Programming 10 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• s.join(sequence) Returns a string comprising elements of the sequence separated by


delimiter s.
Example:

Output will be:

• s.isspace() Returns True if all characters in string s comprise whitespace character only
i.e. space, \n, \t, otherwise returns False.
Example:

Output will be:

• s.isalpha() Returns True if all characters in string s comprise alphabets only, else return
False.
Example:

Python Programming 11 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

• s.isdigit() Returns True if all characters in string s comprise digits only, else return
False.
Example:

Output will be:

• s.isalnum() Returns True if all characters in string s comprise alphabets and digits only,
else return False.
Example:

Output will be:

• s.startswith(str1) Returns True if string s starts with string str1, else return False.
Example:

Output will be:

Python Programming 12 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• s.endswith(str1) Returns True if string s ends with string str1, else return False.
Example:

Output will be:

• s.encode(encoding) Returns s in an encoded form, based on the given encoding


scheme.
Example:

Output will be:

• s.decode(encoding) Returns the decode string s, based on the given encoding scheme.
Example:

Output will be:

Python Programming 13 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

PYTHON LIST
List is an ordered sequence of values. These values can be homogeneous as well as
heterogeneous. Similar to string, every element of list is assigned index (positive and negative
indices).

Creating an Empty List

An empty list can be created by assigning the opening and closing square braces to a variable.

Example:

Output will be:

Creating List with Elements

A list containing elements can be created by writing the comma separated values in between
opening and closing square braces and assigning it to a variable.

Example:

Output will be:

Creating List by creating object of list class

A list can also be created (either empty or filled with elements) by creating an object of list
class.

Example:

Python Programming 14 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

List as input using eval() function

A list can be accepted as input from user using the eval function. While entering the input, the
list elements should be entered within square braces.

Example:

On running the above code, the output will display following line:

User need to enter the communication details as:

The print statement will print the following information as list:

Creating Nested List

A list can contain another list and it is called nested list. A nested list can be defined as:

Example:

Output will be:

It is not necessary that to be a nested list, all the elements of the list should be a list.

Example:

Output will be:

Accessing List Elements using Index

Python Programming 15 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Similar to string, the elements of the list can be accessed using index. To access the elements
from the nested list, two indexes need to be specified. First index tells the position of nested
list and second index specify the position of element within nested list.

Example:

Output will be:

List Operations

Consider the following lists:

• List Multiplication Operator: Repeat the elements of the list.

• List Concatenation Operator: Two or more list can be combined using concatenation
operator.

• List Membership Operator: Checks whether an element is present or not in the list.

• List Slicing: Similar to string, elements of list can be accessed by specifying the index
range.

• Calculating Length of List: Gives the number of elements of the list. Can be calculated
using len() function.

• List Min and Max Functions: To find out the minimum and maximum value from the
list. However, to apply these functions, all the list elements should be of same type i.e.,
list needs to be homogeneous.

• Sum of List Elements: Compute the sum of list elements. It is applicable only if the
list is numeric.

Example:

Python Programming 16 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

List Built-in Functions

• list(s): To convert the sequence s into a list.

Example:

Output will be:

Python Programming 17 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• L.append(e): Inserts the element e at the end of the list L.

Example:

Output will be:

• L.extend(L2): Inserts the items in the sequence L2 at the end of the elements of the
list L.

Example:

Output will be:

• L.remove(e): Removes the first occurrence of the element e from the list.

Example:

Output will be:

Python Programming 18 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• L.pop(i): Returns the element from the list L at index i, while removing it from the
list.

Example:

Output will be:

• L.count(e): Returns count of occurrences of the object e in the list L.

Example:

Output will be:

• L.index(e): Returns index of an object e, if present in the list L.

Example:

Output will be:

Example:

Output will be:

Python Programming 19 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• L.insert(i,e): Inserts element e at index i in the list L.

Example:

Output will be:

• L.sort(): Sorts the elements of the list L.

Example:

Output will be:

• L.reverse(): Reverse the order of elements in the list L.

Example:

Output will be:

Python Programming 20 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Using Del Operator

Del operator can be used to either remove a range of values from the list or to remove the
complete list.

Example:

Output will be:

Example:

Output will be:

List Comprehension

List comprehension is a short hand notation for creating list.

Example:

Output will be:

Python Programming 21 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Using Conditional Statement in List Comprehension

Example:

Output will be:

Creating Nested List along with Conditional Statement in List Comprehension

Example:

Output will be:

Using Nested Loop in List Comprehension

Example:

Output will be:

Python Programming 22 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

List as Argument

When list is used as an argument of the function, then any changes made in the list are reflected
in every function of the code where list is being used.

Example:

Output will be:

Copying List Objects

A list can be copied by following ways:

(i) Using ‘=’ operator: Memory is shared between original and copied list and any
changes made either in original or copied list, are reflected in both lists.

Example:

Output will be:

Output will be:

Python Programming 23 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

(ii) Using copy() function: Separate memory is allocated to original and copied list,
however, in case of nested list, memory is shared between elements of nested list.
So, any changes made in the nested elements of either list (original or copied), are
reflected in both lists.

Example:

Output will be:

Output will be:

(iii) Using deepcopy() function: Separate memory is allocated to original and copied
list, including the nested list elements.

Example:

Python Programming 24 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

Python Programming 25 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

PYTHON TUPLE

Tuple is an ordered sequence of objects but elements of a tuple cannot be overwritten. Like
string, Tuple is immutable.

Creating an Empty Tuple

An empty tuple can be created by assigning the opening and closing braces to a variable.

Example:

Output will be:

Creating Tuple with Elements

A tuple containing elements can be created by writing the comma separated values in between
opening and closing braces and assigning it to a variable.

Example:

Output will be:

Creating Tuple by creating object of Tuple class

A tuple can also be created (either empty or filled with elements) by creating an object of tuple
class.

Example:

Output will be:

Python Programming 26 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Like list, a tuple can be accepted as input from user using the eval function. While entering the
input, the tuple elements should be entered within braces.

When Tuple contains only One Element

If tuple contains only one element, it is called singleton tuple. Tuple element should be accompanied
by a comma to be identified as a tuple, otherwise it will be treated as numeric data type.

Example:

Output will be:

Reassigning the Value of Tuple Element


Example:

Output will be:

Example:

Output will be:

Python Programming 27 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example:

Output will be:

Tuple Operations

Consider the following tuples:

• Tuple Multiplication Operator: Repeat the elements of the tuple.

• Tuple Concatenation Operator: Two or more tuples can be combined using


concatenation operator.

• Tuple Membership Operator: Checks whether an element is present or not in the


tuple.

• Tuple Slicing: Similar to string and list, elements of tuple can be accessed by
specifying the index range.

• Calculating Length of Tuple: Gives the number of elements of the tuple. Can be
calculated using len() function.

• Tuple Min and Max Functions: To find out the minimum and maximum value from
the tuple. However, to apply these functions, all the tuple elements should be of same
type i.e., tuple needs to be homogeneous.

• Sum of Tuple Elements: Compute the sum of tuple elements. It is applicable only if
the tuple is numeric.

Example:

Python Programming 28 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

Tuple Built-in Functions

• tuple(s): To convert the sequence s into a tuple.

Example:

Output will be:

Python Programming 29 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• t.count(e): Returns count of occurrences of element e in tuple t.

Example:

Output will be:

• t.index(e): Returns index of first occurrence of element e in tuple t.

Example:

Output will be:

Python Programming 30 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

PYTHON DICTIONARY

Dictionary is an unordered sequence of key-value pairs, written as ‘key:value’. It is defined


within curly braces and key-value pairs are separated by comma. Keys of the dictionary are
treated as indices of the dictionary. These indices (keys) can be of any immutable type. The
keys of the dictionary are unique i.e., no two key-value pairs can have the same key, however,
values can be repeated.

Creating Empty Dictionary

Empty dictionary can be created by assigning the opening and closing curly braces to a variable.

Example:

Now values can be assigned to empty dictionary as:

Example:

Output will be:

Creating Dictionary with Elements

A dictionary containing elements can be created by writing the comma separated key-value
pairs in between opening and closing curly braces and assigning it to a variable

Example:

Output will be:

Python Programming 31 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example: Creating Dictionary with String as Keys

Output will be:

Example: Creating Dictionary where collection of values are associated with keys

Output will be:

Dictionary Operations

Dictionary operations min(), max(), sum() and membership operator (in and not in) are
defined for keys only.

Consider the following dictionary:

Example: Executing dictionary operations on digits

Python Programming 32 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

Dictionary Built-in Functions

• d.items(): Return an object comprising of tuple of key-value pairs present in dictionary


d.

Example:

Output will be:

• d.keys(): Return an object comprising of all keys of dictionary d.

Example:

Output will be:

• d.values(): Return an object comprising of all values of dictionary d.

Example:

Output will be:

Note: To apply the min(), max(), sum() and membership operator on values of the keys,
d.values() function can be used to access the values and store them in a variable. Then
these operations can be applied.

Example:

Python Programming 33 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

As the values variable contains a list having all values of the dictionary digits and list
support all operations (min(), max(), sum() and membership operator), so can be
applied on variable values.
sum() operations can be applied only, if values contain only numeric values.

Example:

Output will be:

• d.clear(): Remove all key-value pairs from dictionary d.

Example:

Output will be: empty dictionary

Example: Using del operator

Output will be: deallocation of memory assigned to dictionary ‘days’

Python Programming 34 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

• d.get(key, default): For the specified key, the function returns the associated value.
Returns the default value (None) if key is not present in the dictionary d.

Example:

Output will be:

• d1.update(d2): Adds the key-value pairs of dictionary d2 to dictionary d1.

Example:

Output will be:

Changing Value associated with a key

Example:

Output will be:

Printing the Value associated with a key (Using Key as index)

Example:

Output will be:

Python Programming 35 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

PYTHON SETS

Set is an unordered collection of objects without any duplicate. Elements of set are immutable
objects; hence, list cannot be an element of set. Set does not support indexing and slicing
because it is unordered collection. Also, concatenation (+) and multiplication (*) operators
cannot be applied on set.

Creating an Empty Set

Set elements are enclosed within curly braces. But empty set cannot be created by initializing
the variable using opening and closing curly braces. Doing so will create an empty dictionary
because dictionary elements are also enclosed within curly braces. So, empty set is created by
creating an object of set class.

Example:

Output will be:

Creating Set with Elements

Example:

Output will be:

Example: creating the object of set class with values

Output will be:

Set Operations

Python Programming 36 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example:
Consider the following set:
Vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}

Output will be:

Output will be:

Set Built-in Functions

• set(s): convert sequence s into a set.

Example:

Output will be:

• s.add(e): Adds the element e to the set s if not already present.

Python Programming 37 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example:

Output will be:

Example: Adding already existing element in the set

Output will be:

• s.update(L): Adds the items in object L to the set s if not already present.

Example:

Output will be:

• s.remove(e): Removes the element e from the set s.

Example:

Output will be:

• s.pop(): Removes the element e from the set s.

Python Programming 38 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example:

Output will be:

• s.clear(): Removes all elements from the set s.

Example:

Output will be: empty set

Using Del Operator

• s.copy(): Creates a copy of the set s.

Example:

Python Programming 39 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output will be:

Example: Using Copy Module for set

Output will be:

• s1.union(s2): Returns union of set s1 and s2.

Example:

Output will be:

• s1.intersection(s2): Returns a set containing elements common in the sets s1 and s2.

Example:

Output will be:

• s1.difference(s2): Returns a set containing elements in the sets s1 but not in the set s2.

Python Programming 40 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example:

Output will be:

• s1.symmetric_difference(s2): Returns a set containing elements that are in one of the


two sets s1 and s2, but not in both.

Example:

Output will be:

Checking Superset and Subset

Example:

Output will be:

Python Programming 41 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example: Using issubset() and issuperset() function

Output will be:

Python Programming 42 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

USER DEFINED FUNCTIONS

Functions that are not already defined by the programming language and are defined as per the
requirement of the program, are called user defined functions.

To define a function, def keyword is used followed by user defined function name and braces
for parameters and colon sign.

Syntax for defining function in python is:

def function_name(list of parameters):


function statements

Example: Here, CircleArea() is a function defined to compute area of the circle. The last
statement CircleArea() calls the function to execute it.

Output will be:

Types of Arguments/Parameters

• Default parameters (Assigning initial value): Default parameters must not be


followed by non-default parameters.

• Keyword arguments: When order of parameters is different in function definition and


function call.

Default Parameters

Example:

Python Programming 43 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Even if any parameter is not passed while calling the function, the function will compute the
area of the circle using default parameter value.

Output will be: using the default parameter value

If the parameter value is provided while calling the function, then the default parameter value
will be overwritten by this value.

Example:

Output will be:

If we do not provide any default value to parameter, then while calling the function it becomes
mandatory to pass the values for all parameters. Missing any parameter value will result in an
error.

Example:

Output will be:

Output will be:

Python Programming 44 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Example: Using both types of parameters together

Output:

Output:

Example: Order of Default and Non-Default Parameters

Output: Not following order results in error

Keyword Arguments

Using keyword arguments, the order of arguments can be changed. Every argument is defined
along with its value in function definition. While calling the function, same approach is used
(define argument with its value).

Example:

Python Programming 45 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

Output:

Assert Statement

Assert statement is used to check the condition. Program execution stops, if the condition is
false. If the condition is true, then program will execute without any interruption.

Example:

Output:

Importing User Defined Module

Similar to pre-defined modules (provided by python), it is possible to import the user defined
module. Before importing the module, it should be defined as a .py or .pyc (python) file. The

Python Programming 46 HUNNY GAUR


(BCC302) Assistant Professor
Department of Computer Science
IMS Engineering College

path of the file needs to be appended in system path, for which sys module is imported and
sys.path.append() function is called. The path in the append function is till the folder where the
module file is stored.

Example:

Output:

Python Programming 47 HUNNY GAUR


(BCC302) Assistant Professor

You might also like