Unit 3-5
Unit 3-5
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.
Example:
Immutable Strings
• A component of string cannot be altered.
• An attempt to do so would lead to an error.
Example:
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:
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:
Example:
• 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:
• 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:
• s.title( ) Returns a string that has first letter of every word of string s in uppercase.
Example:
• s.swapcase() Converts all uppercase letters of the string s into lowercase and vice versa.
Example:
• s.islower() Returns True if all alphabets in string s are in lowercase, else returns False.
Example:
• s.isupper() Returns True if all alphabets in string s are in uppercase, else returns False.
Example:
• s.strip() Returns a string that has whitespaces in s removed from the beginning and the
end.
Example:
• s.lstrip() Returns a string that has whitespaces in s removed from the beginning.
Example:
• s.rstrip() Returns a string that has whitespaces in s removed from the end.
Example:
• s.split(delimiter) Returns a list formed by splitting the string s into substrings. The
delimiter is used to mark the split points.
Example:
• 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:
• s.isspace() Returns True if all characters in string s comprise whitespace character only
i.e. space, \n, \t, otherwise returns False.
Example:
• s.isalpha() Returns True if all characters in string s comprise alphabets only, else return
False.
Example:
• s.isdigit() Returns True if all characters in string s comprise digits only, else return
False.
Example:
• s.isalnum() Returns True if all characters in string s comprise alphabets and digits only,
else return False.
Example:
• s.startswith(str1) Returns True if string s starts with string str1, else return False.
Example:
• s.endswith(str1) Returns True if string s ends with string str1, else return False.
Example:
• s.decode(encoding) Returns the decode string s, based on the given encoding scheme.
Example:
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).
An empty list can be created by assigning the opening and closing square braces to a variable.
Example:
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:
A list can also be created (either empty or filled with elements) by creating an object of list
class.
Example:
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:
A list can contain another list and it is called nested list. A nested list can be defined as:
Example:
It is not necessary that to be a nested list, all the elements of the list should be a list.
Example:
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:
List Operations
• 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:
Example:
Example:
• L.extend(L2): Inserts the items in the sequence L2 at the end of the elements of the
list L.
Example:
• L.remove(e): Removes the first occurrence of the element e from the list.
Example:
• L.pop(i): Returns the element from the list L at index i, while removing it from the
list.
Example:
Example:
Example:
Example:
Example:
Example:
Example:
Del operator can be used to either remove a range of values from the list or to remove the
complete list.
Example:
Example:
List Comprehension
Example:
Example:
Example:
Example:
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:
(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:
(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:
(iii) Using deepcopy() function: Separate memory is allocated to original and copied
list, including the nested list elements.
Example:
PYTHON TUPLE
Tuple is an ordered sequence of objects but elements of a tuple cannot be overwritten. Like
string, Tuple is immutable.
An empty tuple can be created by assigning the opening and closing braces to a variable.
Example:
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:
A tuple can also be created (either empty or filled with elements) by creating an object of tuple
class.
Example:
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.
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:
Example:
Example:
Tuple Operations
• 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:
Example:
Example:
Example:
PYTHON DICTIONARY
Empty dictionary can be created by assigning the opening and closing curly braces to a variable.
Example:
Example:
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:
Example: Creating Dictionary where collection of values are associated with keys
Dictionary Operations
Dictionary operations min(), max(), sum() and membership operator (in and not in) are
defined for keys only.
Example:
Example:
Example:
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:
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:
Example:
• 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:
Example:
Example:
Example:
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.
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:
Example:
Set Operations
Example:
Consider the following set:
Vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}
Example:
Example:
• s.update(L): Adds the items in object L to the set s if not already present.
Example:
Example:
Example:
Example:
Example:
Example:
• s1.intersection(s2): Returns a set containing elements common in the sets s1 and s2.
Example:
• s1.difference(s2): Returns a set containing elements in the sets s1 but not in the set s2.
Example:
Example:
Example:
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.
Example: Here, CircleArea() is a function defined to compute area of the circle. The last
statement CircleArea() calls the function to execute it.
Types of Arguments/Parameters
Default Parameters
Example:
Even if any parameter is not passed while calling the function, the function will compute the
area of the circle using 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:
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:
Output:
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:
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:
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
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: