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

Python U-3 Notes

The document covers Python's complex data types, focusing on lists, tuples, strings, and sets. It explains the properties, methods, and operations associated with these data types, including mutability, slicing, and built-in functions. Additionally, it includes practical programming exercises and examples to reinforce understanding of these concepts.

Uploaded by

coms1418
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 views107 pages

Python U-3 Notes

The document covers Python's complex data types, focusing on lists, tuples, strings, and sets. It explains the properties, methods, and operations associated with these data types, including mutability, slicing, and built-in functions. Additionally, it includes practical programming exercises and examples to reinforce understanding of these concepts.

Uploaded by

coms1418
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/ 107

PYTHON PROGRAMMING

UNIT 3
COMPLEX DATA TYPE

Today’s Target

List and Tuples


By PRAGYA RAJVANSHI
AKTU PYQs
B.Tech, M.Tech( C.S.E.)
LIST AKTU (2022-23)
at is Stack Organization?
 The list is a sequence data type which is used to
store the collection of data
 Lists in Python can be created by just placing the
sequence inside the square brackets[ ]. .
 list doesn’t need a built-in function for its creation
of a list. .
 the list may contain mutable element
 list may contain duplicate values
with their distinct positions
LIST METHODS (AKTU 2022-23) 3 min() Calculates the minimum of all the elements
1 append() of the List
 Used for adding elements to the end of the List.

2 max()
Calculates the maximum of all the elements of the
List
4 reverse() Reverses objects of the List in place 6.Sort() Sort a List in ascending, descending, or user-
defined order

5 remove() Removes a given object from the List.


. 8insert() method inserts an item at a specific index in
7 pop() Removes and returns the last value from the a list.
List or the given index value.

9 index() method searches for a given element from


the start of the list and returns the position of the
first occurrence.
10 clear() removes all items from the List making
it an empty/null list.

11.Count() returns the count of the occurrences of a


given element in a list.
13 Copy()
A shallow copy creates a new object, but it does not
create new copies of nested objects (like lists inside
a list). Instead, it copies references to those nested
12 extend() objects. So, changes to nested objects affect both
It is method adds items of an iterable (list, tuple,
dictionary, etc) at the end of a list. the original and the copied object.
.
.
LIST ARE MUTUBLE (AKTU 2023-24 ODD)
at is Stack Organization?
 Yes, lists in Python are mutable, which means that
their elements can be changed after the list has
been created. This includes adding, removing, or
modifying elements.
LIST SLICING TO PRINT THE COMPLETE LIST
In order to access a range of elements in a list,
you need to slice a list. One way to do this is to use
the simple slicing operator i.e. colon(:).
Lst[ Initial : End : IndexJump ]

PRINT ONLY 2,3,4 ,5 index element


Write a function to find ASCII value of the character.
1 Print from 4 element of the list then take
jump of 2 upto the end of the list.

Write a program to reverse a list


List comprehension (AKTU 2022-23) Question:- Write a function lessthan (lst,k) to return
It is used to create a new list from the existing list
list of number less than k from the list lst. The
Syntax: newList = [ expression(element) for element
function mnust use list comprehension
in oldList if condition ]
Lessthan([1,-2,0,5,-3],0) returns[-2.-3] (AKTU 2020-
21)
lustrate different list slicing constructs for
the following operations on the following
list:L= [1, 2, 3, 4, 5, 6, 7, 8, 9]
(AKTU 2023-24 ODD)
1. Return a list of numbers starting from
the last to second item of the list
2. Return a list that start from 3rd item
to second last item.
3. Return a list that has only even
position elements of list L.
4. Return a list that starts from the
middle of the list L.
5. Return a list that reverses all the
elements starting from element at
index 0 to middle index only and
return the entire list.
6. Divide each element of the list by 2
and replace it with the remainder.
lustrate different list slicing
constructs for the following operations on
the following list:L= [1, 2, 3, 4, 5, 6, 7, 8, 9]
1. Return a list of numbers starting from
the last to second item of the list
2. Return a list that start from 3rd item
to second last item.
3. Return a list that has only even
position elements of list L to list M.
4. Return a list that starts from the
middle of the list L.
5. Return a list that reverses all the
elements starting from element at
index 0 to middle index only and
return the entire list.
6. Divide each element of the list by 2
and replace it with the remainder.
Write python function,
alternating(lst) that
takes as a argument a
sequence list. The
function return true if
the elements in list are
alternatively odd and
even starting with even
number otherwise it
return false (AKTU 2020-
21)
Write a function make Pairs that
takes as input two lists of equal length
and return a single list of same length
where kth element is the pair of k
element from the input list
For example
Make Pairs([1,,3,4,5],[2,3,4,9])
Return[(1,2),(3,3),(4,4),(5,9)]
Make Pairs([],[])
Returm[] (AKTU 2020-21)
Consider following filter (AKTU 2023-24 ODD)
1 filter all the numbers

2 filter all the string starting with vowels


filters all the strings that contains any of the following noun:
agra ,Ramesh , tomato, Patna
TUPLES(AKTU 2022-23)
atis Stack are similar as list but only difference is  With one item
Organization?
Tuples
that they are immutable
Creating Python Tuples
 Using round brackets

 Tuple Constructor
What is Immutable in Tuples?
 Tuples in Python are similar to Python list but
not entirely. Tuples are immutable and ordered
and allow duplicate values. Some Characteristics
of Tuples in Python.
 We can find items in a tuple since finding any
item does not make changes in the tuple.
 One cannot add items to a tuple once it is
created.
 Tuples cannot be appended or extended.
 We cannot remove items from a tuple once it is
created.
Unpacking a Tuple (AKTU 2023-24 ODD)
In Python, there is a very powerful tuple assignment
feature that assigns the right-hand side of values
into the left-hand side. In another way, it is called
unpacking of a tuple of values into a variable. In
packing, we put values into a new tuple while in
unpacking we extract those values into a single
variable.
Tuple unpacking in Python allows you to assign
elements of a tuple to multiple variables in a single
statement. This is useful when you have a tuple
and want to extract its values directly into separate
variables
Operation on tuples
Accessing Values in Python Tuples

atis Stack
Positive index
Organization?

 Negative index
Write thon program to find repeated items in a remove any item from the tuple

attuple:
is Stack Organization?

Write a program to convert list to tuple


Write a program to reverse the element of the tuple write a program remove duplicate elements from

at is Stack Organization? a list and print the updated list ( AKTU 2023-24)

Write a program to multiply all the element in a tuple. Write a program to add item in tuple
PYTHON PROGRAMMING
UNIT 3
Python Complex data types
By
Pragya Rajvanshi
LEC-1
Today’s target
 String
 some built in function of string

1
String
 A String represents a sequence of characters.
 It is an immutable data type(you have created
a string, you cannot change it.)
 Python Programming does not have a
character data type, a single character is
simply a string with a length of 1.

2
Accessing characters in Python String String slicing
substring = s[start : end : step]
Retrieve All Characters

3
4
String built-in function
1. capitalize() method
 It is used to change the first letter of a string to
uppercase and make all other letters lowercase.

5
2. isalnum() Method 3. isalpha() Method
This method checks whether all the characters It is used to check whether all characters in the
in a given string are either alphabet or numeric String are an alphabet.
(alphanumeric) characters

6
4. isdecimal() Method 5. isdigit() Method
This method checks whether all the It returns “True” if all characters in the string are digits,
characters in a given string is digit. Otherwise, It returns “False”

6. index() Method
The index() method in Python is used to find the position of
a specified substring within a given string.

7
Syntax of index() 7. islower() method
s.index(substring, start=0, end=len(s)) This method checks if all characters in the string are
1. substring: The substring to locate
within the string s. lowercase.
2. start (optional): The starting index
for the search. Defaults to 0 if not
provided.
3. end (optional): The ending index for 8. isnumeric() Method
the search. If not provided, it
defaults to the length of the string. It is used to determine whether the string consists of
numeric characters or not

8
9. isidentifier() Method
 This method is used to check whether
a string is a valid identifier or not
Note:
A string is considered as a valid identifier
if:
 It only consists of alphanumeric
characters and underscore (_)
 Doesn’t start with a space or a
number

9
10. upper() Method 11. isupper() method

 It creates a new string This method returns whether all characters in a string are uppercase or
with all lowercase letters not.
changed to uppercase.
 This method does not
change the original string
instead it simply returns a
new one.
12. lower() Method
It converts all uppercase letters in a string to their lowercase.

10
PYTHON PROGRAMMING

UNIT 3
COMPLEX DATA TYPE

Today’s Target

String
By PRAGYA RAJVANSHI
AKTU PYQs
B.Tech, M.Tech( C.S.E.)
String Len() It can be used to find the length of an object

the Updating or deletion of characters from a String


is not allowed.
String are immutable

Concatenation
.
Write a Python program to get a string made of the first 2 and last 2 characters of a given
string. If the string length is less than 2, return the empty string instead.
write a progarm to take two string and fid out the common letter between them
Write a Python function to get a string made of 4 Write a program to Reverse string if length is a
copies of the last two characters of a specified string multiple of 4
(length must be at least 2)
Write a Python program to change a given string Write a Python program to remove characters that
to a newly string where the first and last chars have have odd index values in a given string.
been exchange
Write a program that accepts a sentence and calculate the Write a program to change a given string
number of digit, uppercase and lowercase (AKTU 2021-22) to a new string where the first and last
chars have been changed(AKTU 2021-
22)
Write a program to count the vowels present in Write a program to check whether a string is a
given input . (AKTU 2022-23) palindrome or not (AKTU 2022-23)
How can you randomize the items of a list in place in python ? (AKTU 2021-22)

What will be the output


Write a program that accepts sequence of lines as input and print the lines after making all character in
the sentence is capitalized(AKTU 2022-23)
Consider a function perfect_square(number) that Split()
returns a number if it is perfect square otherwise
return-1 ( AKTU 2023-24 ODD)
Construct a program that accepts a comma What will be the output. (AKTU 2022-23)
separated sequence of word as an input and prints
the word in a comma- separated sequence after
sorting them alphabetically(AKTU 2023-24 ODD)

Final result is string


Construct a function ret_smaller(l) that return smaller list from a nested list. if two list have same
length then return the first list that is encountered (AKTU 2023-24 ODD)
W rite a Python function to insert a string in the middle of a string.
sets

 A Set in Python is used to store a collection of items


with the following properties.
 No duplicate elements. If try to insert the same item
Note:
again, it overwrites previous one. There is no specific order for set elements to
be printed
 An unordered collection. When we access all items,
they are accessed without any specific order and we
cannot access items using indexes as we do in lists.
 Mutable, meaning we can add or remove elements
after their creation, the individual elements within
the set cannot be changed directly
1. Mutability of Sets (Adding & Removing Elements)
Key points:
add() inserts a new element
remove() deletes an element but raises an error if it's not found.
discard() deletes an element but does not raise an error if it's missing
clear() removes all elements.
2. Elements Inside a Set Must Be Immutable
Although we can modify the set itself, we cannot change the elements inside the set directly.
Attempting to Add a Mutable Element (List)
Using a Tuple Instead of a List Conclusion
 Sets are mutable → We can add or remove
elements.
 Set elements must be immutable → We cannot
modify elements directly.
 Lists and dictionaries cannot be elements of a
 Mutable elements (like lists, dictionaries, set, but tuples and strings can.
sets) cannot be stored in a set
 .Immutable elements (like numbers, strings,
tuples) are allowed.
Heterogeneous Element with Python Set UNION
The union of two sets combines all unique elements
from both sets.
Python sets can store heterogeneous elements
in it, i.e., a set can store a mixture of string,
integer, boolean, etc datatypes.
Intersection Diffrence
Clearing python set
What will be the output ? (AKTU 2022-23)
Write a program to find permutation of a given
string.
Question.1 Which of the following statement X[0]*=3 (AKTU 2020-21)
produce an error in python? It does not give any error . X[0] refers to the string
statement 1: x,y,z=1,2,3 '12'. Multiplying a string by an integer in Python
statement 2: a,b=4,5,6 repeats the string that many times. This updates X[0]
statement 3: u=7,8,9(AKTU 2020-21) to '121212', and now the list X becomes:
Statement 1 give no error Statement 2 gives error X = ['121212', 'hello', 456]
because 6 is not assigned to any variable X[1][1]=‘bye’
Statement 3 gives error as 8,9 is not declared to Here, X[1] refers to the string 'hello', and X[1][1]
any variable refers to the character at index 1 of 'hello', which is
Q2 Explain why this program generate error 'e'. The intention seems to be to replace the
X=[’12’,’hello’,456] character 'e' with the string 'bye'. However, this line
X[0]*=3 generates an error because strings in Python are
X[1][1]=‘bye’ immutable, meaning their individual characters
cannot be changed.
PYTHON PROGRAMMING

UNIT 3
COMPLEX DATA TYPE

Today’s Target

Dictionary , Function
By PRAGYA RAJVANSHI
AKTU PYQs
B.Tech, M.Tech( C.S.E.)
Python Dictionary Method (AKTU 2022-23)
at is Stack Organization?
at is Stack Organization?
at is Stack Organization?
at is Stack Organization?
at is Stack Organization?
at is Stack Organization?
LIST (AKTU 2022-23) DICTIONARY

The dictionary is a hashed structure of the key


The list is a collection of index value pairs like
and value
that of the array in C++.
pairs.

The dictionary is created by placing elements in {


The list is created by placing elements in [
} as “key”:”value”, each key-value pair is
] separated by commas “,”
separated by commas “, “

The elements are accessed via indices. The elements are accessed via key-value pairs.

The order of the elements entered is


There is no guarantee for maintaining order.
maintained.

Lists are orders, mutable, and can contain Dictionaries are unordered and mutable but
duplicate values. they cannot contain duplicate keys.
Append() AKTU (2022-23) Extend()

Append multiple elements fro, an iterable at the


Append single element at the end of the list
end of the list

Accept an iterable (e.g. list,tuple, string) as an


Accepts single element as an argument
argument
List AKTU( 2022-23) tuples

List are mutable Tuples are immutable

List are usually slower than tuples They are faster than list

list1=[10,20,30] Tup1=(10,20,30)
Array AKTU 2019-20) list

Lists are dynamic and can change in size during


Arrays have a fixed size set during creation.
runtime.

All elements in an array must be of the same data Lists can accommodate elements of different data
type. types.

Memory for the entire array is allocated at once Lists dynamically allocate memory as elements are
during initialization. added or removed.

Arrays are less flexible as their size cannot be easily Lists are more flexible, allowing easy addition or
changed. removal of elements.
What will bet the output ? AKTU( 2021-22) Write a python function to convert a decimal number to
its binary ,octal and hexadecimal.
Write a python function removekth (s,k)
that takes as input a string and integer k>=0 and
remove the character at index k. if k is beyond
the length of s, the whole of s is returned
For example
removekth(“python”,2) return pyhon
Removekth(“mango”,1)return mngo
AKTU (2023-24 ODD)
AKTU (2020-21)
Write a program factor(N) that return a list of Write a python program to add item in a tuple.
AKTU (2019-20)
all positive divisor of N (N>=1). AKTU (2020-21)
Write a python code to find out occurrence of an elements in a list.
Write a python program ,count_square(N) that returns the count of perfect square less than or
equal to N(N>=1) for example count_square(1) return 1 only prefect square less than equal to 1
count_square(5 ) return 2 (1, 4 are the prefect square less than equal to 2
count_square(55) return 7 (1,4,9,16,25,36,49)<=55 AKTU (2020-21)
Ques. Write a python function, searchMany(s,x,k) that takes an argument a sequence s and
integersx,k(k>0) the function returns true if there are at most k occurrences of x in s .otherwise it returns
false searchMany ([10,17,15,12],15,1) return true, searchMany([10,12,12,12],12,2) return falseAKTU
(2020-21)
A website requires the users to input username and password to register. Construct a program to
check the validity of password input by users. Following are the criteria for checking the password
(Aktu 2023-24 ODD
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12
7. Your program should accept a sequence of comma separated passwords and will check them
according to the above criteria. Passwords that match the criteria are to be printed, each separated
by a comma
The import re statement in Python is used to import the re module, which provides support for working
with regular expressions. Regular expressions (regex) are patterns used to match character
combinations in strings. The re module allows you to perform tasks such as searching, matching, and
replacing text using these patterns.
FUNCTION

 Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the same
code again and again for different inputs, we can do the function calls to reuse code contained in it
over and over again.
 Some Benefits of Using Functions
 Increase Code Readability
Increase Code Reusability
Types of Functions in Python
There are mainly two types of functions in Python
 Built-in library function: These are Standard functions in Python that are available to use.
 User-defined function: We can create our own functions based on our requirements.
Python Function Declaration
Python Function

 Syntax of function definition :


 def function name( arg 1, arg 2):
{
…..
}
Syntax of function call
Function_name( arg1,arg2)
Python Function

 Keyword: the keyword ‘def’ is used to define function header.


 Function name: we define the function name for identification or to uniquely identify the function.
 ( : ) a colon to mark the end of function header.
 Arguments these are the values passed to the function between parentheses
 Body of the function: the body process the argument to do something use ful
 An optional return statement to return the value from the function.
 function call To execute a function , we have to call it
Creating a Function in Python

 We can define a function in Python, using the def keyword. We can add any type of functionalities and
properties to it as we require.
Python Function with Parameters

 If you have experience in C/C++ or Java then you must be thinking about the return type of
the function and data type of arguments. That is possible in Python as well (specifically for
Python 3.5 and above).
 Defining and calling a function with parameters
 def function_name(parameter: data_type) -> return_type:
 """Docstring"""
 # body of the function
 return expression.
Python Function with Parameters
Types of Python Function Arguments AKTU (2022-23)

 Python supports various types of arguments that can be passed at the time of the function
call. In Python, we have the following 4 types of function arguments.
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments

 A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument
Keyword Arguments

 The idea is to allow the caller to specify the argument name with values so that the caller does not
need to remember the order of parameters.
Keyword Arguments

 Keyword-only arguments mean whenever we pass the arguments(or value) by their


parameter names at the time of calling the function in Python in which if you change the
position of arguments then there will be no change in the output.
 Benefits of using Keyword arguments over positional arguments
 On using keyword arguments you will get the correct output because the order of argument
doesn’t matter provided the logic of your code is correct. But in the case of positional
arguments, you will get more than one output on changing the order of the arguments..
Positional Arguments

 Position-only arguments mean whenever we pass the arguments in the order we have defined function
parameters in which if you change the argument position then you may get the unexpected output. We
should use positional Arguments whenever we know the order of argument to be passed.
 So now, we will call the function by using the position-only arguments in two ways, and In both cases,
we will be getting different outputs from which one will be correct and another one will be incorrect

 We used the Position argument during the function call so that the first argument (or value) is assigned
to name and the second argument (or value) is assigned to age. By changing the position, or if you
forget the order of the positions, the values can be used in the wrong places, as shown in the Case-2
example below, where 27 is assigned to the name and Suraj is assigned to the age
Positional Arguments
Arbitrary Keyword Arguments

 In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
*args in Python (Non-Keyword Arguments)

 We can declare a variable length length argument with the*symbol


 The *args allows a function to accept any number of positional arguments
 The arguments are collected as a tuple within the function
*args in Python (Non-Keyword Arguments)
***kwargs in Python (Keyword Arguments)

 The *kwargs parameter allows a function to accept any number of keyword arguments.
 The arguments are collected as a dictionary within the function
Calculator using function AKTU (2019-20)
Calculator using function
Calculator using function
Python Scope variable AKTU (2019-20)

 The location where we can find a variable and also access it if required is called the scope of a variable
 Python Local variable
 Local variables are those that are initialized within a function and are unique to that function. It
cannot be accessed outside of the function
Python Scope variable

 Python Local variable


 If we will try to use this local variable outside the function
Python Scope variable
 Python Global variables
 Global variables are the ones that are defined and declared outside any function and are not
specified to any function. They can be used by any part of the program.
GENERATORS(AKTU 2023-24)
 A generator function is like a normal
function but uses the yield keyword
instead of return.
 When called, it does not execute
immediately but returns a generator
object (an iterator).
 This generator object can be used to fetch
values one by one using next().
 The function remembers its state after
yielding a value and resumes execution
when next() is called again.
lambda function
 Python Lambda Functions are anonymous
functions means that the function is without a
name.
 As we already know the def keyword is used to
define a normal function in Python.
 Similarly, the lambda keyword is used to define an
anonymous function in Python.
SYNTAX:
Syntax: lambda arguments : expression
 lambda: The keyword to lambda function to add two numbers
define the function.
 arguments: A comma-
separated list of input
parameters (like in a
Square a Number
regular function).
 expression: A single
expression that is
evaluated and returned.
How lambda function can be used within In a list comprehension
You can use lambda functions inside list comprehensions to perform quick operations on
elements.
Write a python program that use lambda function within a list comprehension to convert the list
of temperature in Celsius to Fahrenheit
Find the LCM OF TWO NUMBER
Thank You

You might also like