0% found this document useful (0 votes)
7 views37 pages

Unit - 3 Notes Python

The document covers Python complex data types, focusing on string, list, tuple, and dictionary data types, including their creation, manipulation methods, and built-in functions. It explains string operations, list slicing, tuple characteristics, and dictionary key-value pairs, emphasizing the immutability of tuples and the mutability of lists and dictionaries. Additionally, it highlights the importance of functions in Python for code reusability and readability.

Uploaded by

mohdsameer10841
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views37 pages

Unit - 3 Notes Python

The document covers Python complex data types, focusing on string, list, tuple, and dictionary data types, including their creation, manipulation methods, and built-in functions. It explains string operations, list slicing, tuple characteristics, and dictionary key-value pairs, emphasizing the immutability of tuples and the mutability of lists and dictionaries. Additionally, it highlights the importance of functions in Python for code reusability and readability.

Uploaded by

mohdsameer10841
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

BCC 302: Python Programming

Unit 3: Python Complex Data Types

Using string data type and string operations, defining list and list slicing, use of Tuple data type.
String, List and Dictionary, Manipulation Building blocks of Python programs, string
manipulation methods, List manipulation method. Dictionary manipulation, Programming using
string, list and dictionary in -built functions. Python Functions, organizing python codes using
functions.

USING STRING DATA TYPES AND STRING OPERATION

String: String is a datatype which consists of a sequence of letters, characters, numbers,


punctuations and spaces. In Python, a string is considered as an array of bytes with each byte
representing a character. Python does not have a character datatype, rather a single character is
simply a string with one character or length equals 1.

Creating a String

Single quotes or double quotes are used to represent a string in Python.

Example:

Multiline String

Multiline string can be created by using three quotes.


Access String Characters in Python

We can access the characters in a string in three ways.

1. Indexing: Each of a string’s characters corresponds to an index number, starting with the
index number 0.

Syntax: string_var[index]

Example:

2. Slicing: To access a range of characters in a string by using the slicing operator colon (:).
Specify the start index and the end index, separated by a colon, to return a part of the
string.

Syntax: string_var[start: end: step]

Slice From the Start: By leaving out the start index, the range will start at the first
character:

Slice To the End: By leaving out the end index, the range will go to the end:
Negative Indexing: Use negative indexes to start the slice from the end of the string:

Immutability: Strings cannot be modified or changed, i.e., they are immutable. Once a string is
created, we cannot modify the string. But a new variable can be created to achieve the same
action.

Example:

String Operations

Concatenation: To concatenate, or combine, two strings you can use the + operator.

Repetition: To repeat a string we can use * operator.

Check String: To check if a certain phrase or character is present in a string, we can use the
keyword in.
Check if not: To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.

DEFINING LIST AND LIST SLICING

 Lists are used to store multiple items in a single variable.


 Lists are one of 4 built-in data types in Python used to store collections of data, the other
3 are Tuple, Set, and Dictionary, all with different qualities and usage.
 Lists are created using square brackets:

 Creating an Empty List:

 List items are ordered, changeable, and allow duplicate values.


 List items are indexed, the first item has index [0], the second item has index [1] etc.
 A list can contain different data types.

Accessing List Items

List items are indexed and can be accessed by referring to the index number.
List items can also be accessed by using negative indexing. Negative indexing means start from
the end. -1 refers to the last item, -2 refers to the second last item etc.

List Slicing

List slicing lets us easily access specific elements in a list.

Syntax: list_name[start : end : step]

Parameters:

 start (optional): Index to begin the slice (inclusive). Defaults to 0 if omitted.


 end (optional): Index to end the slice (exclusive). Defaults to the length of the list if omitted.
 step (optional): Step size, specifying the interval between elements. Defaults to 1 if
omitted.

Get all the items from a list

To retrieve all items from a list, we can use slicing without specifying any parameters.

Get all items before/after a specific position

To get all the items from a specific position to the end of the list, we can specify the start index
and leave the end blank.

And to get all the items before a specific index, we can specify the end index while leaving start
blank.
Get all items between two positions

To extract elements between two specific positions, specify both the start and end indices.

Get items at specified intervals

To extract elements at specific intervals, use the step parameter.

Slicing using Negative Indexing


Output:

Reverse a list using slicing

By using a negative step value, we can move through the list in reverse order.

Modifying items in a List

To change the value of a specific item, refer to the index number:

To change the value of items within a specific range, define a list with the new values, and refer
to the range of index numbers where you want to insert the new values:
insert() method: To insert a new list item, without replacing any of the existing values, we can
use the insert() method. The insert() method inserts an item at the specified index:

append() method: To add an item to the end of the list, use the append() method.

extend() method: To append elements from another list to the current list, use the extend()
method.

List Comprehension

List comprehension in Python offers a concise way to create lists based on existing iterables. It
provides a more readable and often faster alternative to traditional for loops when constructing
lists.

Syntax: [expression for item in iterable if condition]

 expression: The operation performed on each item.


 item: A variable representing each element in the iterable.
 iterable: The sequence (e.g., list, tuple, range) being processed.
 condition (optional): Filters elements based on a boolean expression.

Example: 1. Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional test inside.

2. To create a list of squares from 1 to 10

3. To include a condition, such as filtering for even squares

USE OF TUPLE DATA TYPE, STRING, LIST AND DICTIONARY

Tuple

A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but
unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can
hold elements of different data types. The main characteristics of tuples are being ordered,
heterogeneous and immutable.

Creating a Tuple

A tuple is created by placing all the items inside parentheses (), separated by commas. A tuple
can have any number of items and they can be of different data types.
Create Tuple with One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python
will not recognize it as a tuple.

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

Accessing a Tuple

The elements of a tuple can be accessed by using indexing and slicing, similar to how we access
elements in a list. Indexing starts at 0 for the first element and goes up to n-1, where n is the
number of elements in the tuple. Negative indexing starts from -1 for the last element and goes
backward.
Output:

Concatenation of Tuples

Tuples can be concatenated using the + operator. This operation combines two or more tuples to
create a new tuple.

Output:

Repeating Sequence

Repeating a sequence in tuples is achieved using the “*” operator.

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 again, it overwrites previous one.
 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.

Sets are written with curly brackets.

Dictionary

A Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated
and must be immutable.

From Python 3.7 Version onward, Python dictionary are Ordered.

Dictionary keys are case sensitive: the same name but different cases of Key will be treated
distinctly.

Keys must be immutable: This means keys can be strings, numbers, or tuples but not lists.

Keys must be unique: Duplicate keys are not allowed and any duplicate key will overwrite
the previous value.

Dictionary internally uses Hashing. Hence, operations like search, insert, delete can be
performed in Constant Time.

Creating a Dictionary

In Python, a dictionary can be created by placing a sequence of elements(key: value pair)


within curly {} braces, separated by a 'comma'.

Example:
The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary.

Accessing Dictionary Items

We can access a value from a dictionary by using the key within square brackets or get() method.

Syntax: dict_var[key]

Example:

keys(): The keys() method will return a list of all the keys in the dictionary.
values(): This method will return a list of all the values in the dictionary.

Adding and Updating Dictionary Items

We can add new key-value pairs or update existing keys by using assignment.
Copy a Dictionary

We cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a
reference to dict1, and changes made in dict1 will automatically also be made in dict2.

copy(): Make a copy of a dictionary with the copy() method.

Syntax: new_dict = dict_var.copy()

dict(): Make a copy of a dictionary with the dict() function.

Syntax: new_dict = dict(dict_var)

STRING MANIPULATION METHODS

Python has a set of built-in methods that you can use on strings. All string methods return new
values. They do not change the original string.
Method Description Example

Converts the first


capitalize() character to upper
case

Converts string
casefold()
into lower case

center(width, Returns a centered


fillchar) string

Returns the
number of times a
count()
specified value
occurs in a string
Returns an
encode() encoded version
of the string

Returns true if the


endswith() string ends with
the specified value

Sets the tab size of


expandtabs()
the string.

Searches the string


for a specified
value and returns
find()
the position of
where it was
found.
formats the
specified value(s)
format() and insert them
inside the string's
placeholder.
Accepts a
mapping object
and returns a
formatted string
format_map() with the
placeholders
replaced by their
corresponding
values from the
mapping.
Searches the string
for a specified
value and returns
index()
the position of
where it was
found.
Returns True if all
characters in the
isalnum()
string are
alphanumeric.

Returns True if all


characters in the
isalpha()
string are in the
alphabet.

Returns True if all


characters in the
isascii()
string are ascii
characters.

Returns True if all


characters in the
isdecimal()
string are
decimals.

Returns True if all


isdigit() characters in the
string are digits.
Returns True if
isidentifier() the string is an
identifier.

Returns True if all


characters in the
islower()
string are lower
case

Returns True if all


isnumeric() characters in the
string are numeric.
Returns True if all
isprintable() characters in the
string are printable

Returns True if all


characters in the
isspace()
string are
whitespaces

Returns True if
istitle() the string follows
the rules of a title

Returns True if all


characters in the
isupper()
string are upper
case

Joins the elements


join() of an iterable to
the end of the
string
Returns a left
ljust() justified version
of the string

Converts a string
lower()
into lower case

Returns a left trim


lstrip() version of the
string

Returns a tuple
where the string is
partition()
parted into three
parts

Returns a string
where a specified
replace() value is replaced
with a specified
value

Searches the string


for a specified
rfind() value and returns
the last position of
where it was
found
Searches the string
for a specified
rindex() value and returns
the last position of
where it was
found
Returns a right
rjust() justified version of
the string

Returns a tuple
where the string is
rpartition()
parted into three
parts

Returns a right
rstrip() trim version of the
string

Splits the string at


the specified
split()
separator, and
returns a list
Splits the string at
splitlines() line breaks and
returns a list

Returns true if the


startswith() string starts with
the specified value

Returns a trimmed
strip() version of the
string.

Swaps cases,
lower case
swapcase()
becomes upper
case and vice
versa
Converts the first
title() character of each
word to upper case

Converts a string
upper()
into upper case
Fills the string
with a specified
zfill()
number of 0
values at the
beginning

LIST MANIPULATION METHOD

PROGRAMMING USING STRING, LIST AND DICTIONARY IN-BUILT FUNCTIONS

Built-in Functions with Strings

Following are the built-in functions we can use with strings –

S. No. Function Description Example


Returns the length of the
1 len(string_var)
string.

Returns the max


2 max(string_var) alphabetical character
from the string str.

Returns the min


3 min(string_var) alphabetical character
from the string str.

Built-in Functions Dictionary

Here is a list of built-in functions for dictionaries in Python:

clear(): Removes all items from the dictionary.

copy(): Returns a shallow copy of the dictionary.

fromkeys(sequence, [value]): Creates a new dictionary with keys from sequence and values set to
value (default is None).

get(key, [default]): Returns the value for key if key is in the dictionary, else returns default
(None if not specified).

items(): Returns a view object that displays a list of a dictionary's (key, value) tuple pairs.

keys(): Returns a view object that displays a list of all the keys in the dictionary.

pop(key, [default]): Removes the key and returns its value or returns default if the key is not

found. popitem(): Removes and returns an arbitrary (key, value) pair from the dictionary.

setdefault(key, [default]): Returns the value of the key if in the dictionary. If not, it inserts the
key with a value of default (None if not specified).

update([other]): Updates the dictionary with the key/value pairs from other, overwriting existing
keys.
values(): Returns a view object that displays a list of all the values in the dictionary.

dict(): Creates a new dictionary. It can be used with or without arguments.

len(): Returns the number of items (key-value pairs) in the dictionary.

str(): Returns a string representation of the dictionary.

in: Checks if a key exists in the dictionary.

not in: Checks if a key does not exist in the dictionary.

del: Deletes an item or the entire dictionary.

PYTHON FUNCTIONS

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

 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.

Creating a User Defined Function

In Python a function is defined using the def keyword, followed by the name of the function and
parenthesis. After the parenthesis, a colon is used to signify the start of the function body.

Syntax:
Example:

Calling a Function in Python

After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function.

Example:

Docstring
The first string after the function is called the Document string or Docstring in short. This is used
to describe the functionality of the function. The use of docstring in functions is optional but it is
considered a good practice.

Syntax: print(function_name. doc )

Example:

Parameters or Arguments

The terms parameter and argument is the information that is passed into a function.

From a function's perspective:

 A parameter is the variable listed inside the parentheses in the function definition.
 An argument is the value that is sent to the function when it is called.

Types of Python Function Arguments

Python supports various types of arguments that can be passed at the time of the function call. In
Python, we have the following function argument types in Python:

 Default argument
 Keyword arguments (named arguments)
 Positional 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.

Example:

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.

Example:
Positional Arguments: Positional arguments are values passed to a function where their position
determines the corresponding parameter they are assigned to. The order of these arguments in the
function call must match the order of the parameters in the function definition.

Example:

Variable Length Arguments: In Python, functions can be designed to accept a variable number
of arguments using *args and **kwargs.

 Arbitrary Arguments (*args) is used to pass a variable number of non-keyworded


arguments. These arguments are collected into a tuple within the function.
Example:
 Arbitrary Keyword Arguments (**kwargs) is used to pass a variable number of
keyworded arguments. These arguments are collected into a dictionary within the
function. Example:

Python Function within Functions

A function that is defined inside another function is known as the inner function or nested
function. Nested functions can access variables of the enclosing scope. Inner functions are used
so that they can be protected from everything happening outside the function.
Anonymous Function in Python

An anonymous function in Python, also known as a lambda function, is a function that is defined
without a name. It is created using the lambda keyword, and it can take any number of arguments
but can only have one expression. Lambda functions are often used for short, simple operations
where a full function definition is not necessary.

Syntax: lambda arguments: expression

lambda: keyword indicating the start of an anonymous function.

arguments: comma-separated list of input arguments.

expression: single expression that is evaluated and returned.

Example:

Recursive Functions in Python


Recursion in Python refers to when a function calls itself. There are many instances when you
have to build a recursive function to solve Mathematical and Recursive Problems.

Using a recursive function should be done with caution, as a recursive function can become like
a non-terminating loop. It is better to check your exit statement while creating a recursive
function.
IMPORTANT QUESTIONS

Q1. What do you mean by recursion? Write a recursive function to compute the factorial of an
input number N.

Q2. A. Describe the concept of list comprehension with a suitable example.

B. Compare list and tuple.

C. Explain the output of the following code:

Q3. A) Compute the output of the following python code:

def count(s):

for str in string.split():

s = “&”.join(str)

return s

print(count(“Python is fun to learn.”))

B) What is the output of the following program? (lambda x,y : y - 2*x) (1, 11)

Q4. A. Explain why the program generates an error.

x = [‘12’, ’hello’, 456]

x[0] *= 3

x[1][1]=’bye’

B. What is the difference between Python Arrays and Lists?


Q5. Illustrate 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.

Divide each element of the list by 2 and replace it with the remainder.

Q6. Construct a function perfect_square(number) that returns a number if it is a perfect square


otherwise it returns -1.

For example:

perfect_square(1) returns 1

perfect_square (2) returns -1

Q7. Determine a python function removenth(s,n) that takes an input a string and an integer
n>=0 and removes a character at index n. If n is beyond the length of s, then whole s is
returned. For example:

removenth(“MANGO”,1) returns MNGO

removenth(“MANGO”,3) returns MANO

Q8. Construct a function ret smaller(l) that returns smallest list from a nested list. If two lists
have same length then return the first list that is encountered. For example:

ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [3, 4, 5], [6 , 7, 8, 9, 10], [11, 12, 13, 14, 15]]) returns [3,4,5]

ret smaller([ [ -2, -1, 0, 0.12, 1, 2], [‘a’, ’b’, ’c’, ’d’, 3, 4, 5], [6 , 7, 8, 9, 10], [11, 12, 13, 14, 15]])
returns [6 , 7, 8, 9, 10]

Q9. Construct following filters:


1. Filter all the numbers

2. Filter all the strings starting with a vowel

3. Filter all the strings that contains any of the following noun: Agra,

Ramesh, Tomato, Patna.

Create a program that implements these filters to clean the text.

Q10. Write a recursive Python function “rprint” to print all elements in a list in reverse.

rprint([]) prints nothing

rprint([1,2,3]) prints 3 2 1

Q11. Write a function lessthan(lst, k) to return list of numbers less than k from a list lst. The
function must use list comprehension.

Example: lessthan([1, -2, 0, 5, -3], 0) returns [-2, -3]

Q12. Write a program factors(N) that returns a list of all positive divisors of N (N>=1). For
example:

factors(6) returns [1,2,3,6]

factors(1) returns [1]

factors(13) returns [1,13]

Q13. Write a function makePairs that takes as input two lists of equal length and returns a
single list of same length where k-th element is the pair of k-th elements from the input lists. For
example,

makePairs([1,3,5,7],[2,4,6,8]) returns [(1,2),(3,4),(5,6),(7,8)]

makePairs([],[]) returns []

Q14. Show an example where both Keyword arguments and Default arguments are used for the
same function in a call. Show both the definition of the function and its call.
Q15. Write a Python program, countSquares(N), that returns the count of perfect squares less
than or equal to N (N>1). For example:

countSquares(1) returns 1

# Only 1 is a perfect square <= 1

countSquares(5) returns 2

# 1, 4 are perfect squares <= 5

countSquares(55) returns 7

# 1, 4, 9, 16, 25, 36, 49 <= 55

Q16. Write a Python function, alternating(lst), that takes as argument a sequence lst. The
function returns True if the elements in lst are alternately odd and even, starting with an even
number. Otherwise it returns False. For example:

alternating([10, 9, 9, 6]) returns False

alternating([10, 15, 8]) returns True

alternating([10]) returns True

alternating([]) returns True

alternating([15, 10, 9]) returns False

Q17. Write a Python function, searchMany(s, x, k), that takes as argument a sequence s and
integers x, k (k>0). The function returns True if there are at most k occurrences of x in s.
Otherwise it returns False. For example:

searchMany([10, 17, 15, 12], 15, 1) returns True

searchMany([10, 12, 12, 12], 12, 2) returns False

searchMany([10, 12, 15, 11], 17, 18) returns True

Q18. Explain unpacking sequences, mutable sequences with examples. Write a program to sort
list of dictionaries by values in Python- using a lambda function.
Q19. Write a Python function to count occurrences of an element in list.

Q20. Discuss the function in Python with its parts and scope. Explain with example. Make a
simple calculator with add, subtract, division and multiplication.

Q21. Discuss list data structure in python. Explain various in-built methods of list with suitable
examples of each.

Q22. Compare list and the dictionary. Explain various dictionary methods with suitable
examples.

You might also like