0% found this document useful (0 votes)
17 views18 pages

Unit II

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

Python Programming

Unit - III

 Introduction to Collection list :

 The basic data structures used to store and manage several items in Python are called
collections.
 They come in a variety of formats, including as
 lists[],
 tuples(),
 sets{},
 and dictionaries {key : value},
and are necessary for many programming tasks.
 In addition to these fundamental collection types, Python offers a built-in module called
"collections,"
 It adds additional data structures to handle particular requirements and constraints of the
fundamental collection types.

 Basic Collection Data Types:

 List: var_name = [ value1, value2, value3 ]


 A list is declared using square brackets and is a mutable collection,
 allowing the addition, modification, and removal of elements.
 Lists can contain duplicate values and multiple data types are accessed using index values.
Syntax:

var_name = [value1,value2,value3]
Li = ['prasad',True,10,15.4598]

 Tuple: var_name = (value1, value2, value3)


 A tuple is an ordered and immutable collection
 often used to group related values together.
 While tuples can have duplicate entries, and different data types
 their values cannot be changed after creation.
Syntax:

var_name = (value1,value2,value3)
tup = ('prasad',True,10,15.4598)

 Set: set = {value1, value2, value3}


 A set is an unordered collection declared in curly brackets.
 It does not allow duplicate entries, making it suitable for tasks that require unique elements.
 Sets do not support indexing.
Syntax:

set = {value1,value2,value3}

Page 1 of 18
Python Programming
Unit - III

set = {'prasad',10,10.56,True}

 Dictionary: var_name = { key : value }


 A dictionary is a mutable collection that stores key-value pairs.
 It is declared using square brackets and supports efficient retrieval of values using keys.
Syntax:
var_name = {key : value}
Prn_No = {'Prasad':375, 'Rahul': 373}

 Lists in python:
 In Python programming, "lists" are essential data
structures.
 A list is a collection of data items that are stored
in a sequence.
 List can have multiple data types in one
 They play a crucial role and are used for various
tasks.
 List items are indexed, the first item has index
[0], the second item has index [1] etc.
 Lists can be created using square brackets[ ]
 Lists are mutable(changable) which means we can change the values of list after defining

 Characteristics of list:

#1. Order:
 Lists maintain the order in which elements are added, ensuring predictability and
consistency in accessing data.

#2. Indexing:
 Elements within a list can be accessed through indices, which start from 0.
 This concept of 0-based indexing is pivotal to navigating and manipulating list items.

#3. Mutability:
 Lists are mutable, meaning their contents can be modified even after their creation.
 Elements can be added, removed, or altered seamlessly.

#4. Heterogeneity:
 Lists are remarkably versatile and can accommodate elements of diverse data types.
 This flexibility is invaluable when dealing with multifaceted datasets.

Output :

Page 2 of 18
Python Programming
Unit - III

Program: [10, 20, 50, -50, 80, 100]


li1 = [10,20,50,-50,80,100] <class 'list'>
print(li1) --------------------------
print(type(li1)) ['prasad', 'rahul']
print("--------------------------") <class 'list'>
--------------------------
li2 = ['prasad', 'rahul'] ['prasad', True, 10, 15.4598]
print(li2) <class 'list'>
print(type(li2)) <class 'str'>
print("--------------------------") <class 'bool'>
<class 'int'>
li3 = ['prasad',True,10,15.4598] <class 'float'>
print(li3)
print(type(li3))
print(type(li3[0]))
print(type(li3[1]))
print(type(li3[2]))
print(type(li3[3]))

 Python lists provide a range of built-in methods that facilitate efficient manipulation and
management of list elements. These methods include:

1. append( ):
 Adds an element to the end of the list.
2. clear( ):
 Removes all elements from the list.
3. copy( ):
 Creates a shallow copy of the list.
4. count( ):
 Returns the number of occurrences of a specific element.
5. extend( ):
 Adds elements from another list or iterable to the end of the current list.
6. index( ):
 Returns the index of the first occurrence of a specific element.
7. insert( ):
 Inserts an element at a specific position in the list.
8. pop():
 Removes and returns an element at a specific index.
9. remove( ):
 Removes the first occurrence of a specific element.
10. reverse( ):
 Reverses the order of elements in the list.
11. sort( ):

Page 3 of 18
Python Programming
Unit - III

 Sorts the list in ascending order (by default) or using a custom sorting function.
Program:

li = [3, 5, 2, 8, 5, 2]
print("Origional list:",li)

# append(): Adds an element to the end of the list.


li.append(10)
print("After append():", li)

# copy(): Creates a shallow copy of the list.


li2 = li.copy()
print("Copy of the list:", li2)

# count(): Returns the number of occurrences of a specific element.


count = li.count(5)
print("Count of 5:", count)

# extend(): Adds elements from another list or iterable to the end of the current list.
li.extend([7, 9])
print("After extend():", li)

# index(): Returns the index of the first occurrence of a specific element.


index = li.index(8)
print("Index of 8:", index)

# insert(): Inserts an element at a specific position in the list.


li.insert(2, 4)
print("After insert():", li)

# pop(): Removes and returns an element at a specific index.


pop = li.pop(4)
print("Popped element:", pop)
print("After pop():", li)

# remove(): Removes the first occurrence of a specific element.


li.remove(5)
print("After remove():", li)

# reverse(): Reverses the order of elements in the list.


li.reverse()
print("After reverse():", li)

Page 4 of 18
Python Programming
Unit - III

# sort(): Sorts the list in ascending order.


li.sort()
print("After sort():", li)

# clear(): Removes all elements from the list.


li.clear()
print("After clear():", li)

Output:

Origional list: [3, 5, 2, 8, 5, 2]


After append(): [3, 5, 2, 8, 5, 2, 10]
Copy of the list: [3, 5, 2, 8, 5, 2, 10]
Count of 5: 2
After extend(): [3, 5, 2, 8, 5, 2, 10, 7, 9]
Index of 8: 3
After insert(): [3, 5, 4, 2, 8, 5, 2, 10, 7, 9]
Popped element: 8
After pop(): [3, 5, 4, 2, 5, 2, 10, 7, 9]
After remove(): [3, 4, 2, 5, 2, 10, 7, 9]
After reverse(): [9, 7, 10, 2, 5, 2, 4, 3]
After sort(): [2, 2, 3, 4, 5, 7, 9, 10]
After clear(): []

 These are just a few of the basic list methods that Python offers.
 They provide the foundation for various data manipulation tasks involving lists.
 Remember that lists in Python can hold a diverse range of data types, making them a versatile
tool for various programming scenarios.

 Introduction to Tuples:

 Tuples in Python are a collection of


objects that are ordered and
immutable. (Non-Changable)

 They are similar to lists in terms of


indexing, nested objects, and
repetition.

 key difference is that tuples are


immutable(Non-Changable) while lists are mutable(Changable).

 Tuple elements can be accessed using indexes.

Page 5 of 18
Python Programming
Unit - III

 The index of the first element in a tuple is 0, the index of the second element is 1, and so on.

 Tuple elements cannot be modified after they are created. If you try to modify a tuple element,
you will get an error

 Tuple elements cannot be added or removed after they are created,

 There are many other operations that can be performed on tuples in Python. For example, you
can sort a tuple, reverse a tuple, or check if an element is in a tuple,

 Tuples can contain any data type, including numbers, strings, lists, and other tuples.
 Tuples can be nested, meaning that a tuple can contain another tuple.

 Characteristics of tuples:

#1. Ordered Collection:


 Tuples are ordered, meaning that the elements within a tuple have a specific order, and that
order is maintained.
 The first element has an index of 0, the second has an index of 1, and so on.

#2. Immutable:

 Once a tuple is created, its elements cannot be changed, added, or removed.


 Tuples are immutable, which ensures the data's integrity and prevents accidental changes to the
elements.

#3. Allow Duplicates:

 Tuples can contain duplicate values.


 This means you can have multiple occurrences of the same value within a tuple.

#4. Mixed Data Types:


 Tuples can contain elements of different data types.
 For instance, a tuple can store a combination of strings, integers, floats, and other data types.

Program:
tpl1 = (10,20,50,-50,80,100)
Output:

(10, 20, 50, -50, 80, 100)


<class 'tuple'>
--------------------------

Page 6 of 18
Python Programming
Unit - III

print(tpl1) ('prasad', 'rahul')


print(type(tpl1)) <class 'tuple'>
print("--------------------------") --------------------------
('prasad', True, 10, 15.4598)
<class 'tuple'>
tpl2 = ('prasad', 'rahul')
<class 'str'>
print(tpl2)
<class 'bool'>
print(type(tpl2))
<class 'int'>
print("--------------------------")
<class 'float'>
tpl3 = ('prasad',True,10,15.4598)
print(tpl3)
print(type(tpl3))
print(type(tpl3[0]))
print(type(tpl3[1]))
print(type(tpl3[2]))
print(type(tpl3[3]))

Alike list’s Python tuple also provide a range of built-in methods that facilitate efficient
manipulation and management of list elements. These methods include:

1. len():
 This function returns the length of a tuple.
2. min():
 This function returns the minimum value in a tuple.
3. max():
 This function returns the maximum value in a tuple.
4. sum():
 This function returns the sum of the values in a tuple.
5. sorted():
 This function sorts the elements of a tuple in ascending order.
6. reversed():
 This function reverses the elements of a tuple.
7. tuple():
 This function converts a list or a string to a tuple.

Program:
# Creating a sample tuple
tup = (5, 2, 8, 3, 1, 9, 6)

# len(): Returns the length of the tuple


length = len(tup)
print(f"Length of the tuple: {length}")

Page 7 of 18
Python Programming
Unit - III

# min(): Returns the minimum value in the tuple


minimum = min(tup)
print(f"Minimum value in the tuple: {minimum}")

# max(): Returns the maximum value in the tuple


maximum = max(tup)
print(f"Maximum value in the tuple: {maximum}")

# sum(): Returns the sum of values in the tuple


total = sum(tup)
print(f"Sum of values in the tuple: {total}")

# sorted(): Returns a sorted tuple in ascending order


sort = sorted(tup)
print(f"Sorted tuple: {sort}")

# reversed(): Returns a reversed tuple


rev = tuple(reversed(tup))
print(f"Reversed tuple: {rev}")
# Convert a list to a tuple using tuple()
li = [10, 20, 30]
convert = tuple(li)
print(f"Converted tuple from a list: {convert}")

Output:
Length of the tuple: 7
Minimum value in the tuple: 1
Maximum value in the tuple: 9
Sum of values in the tuple: 34
Sorted tuple: [1, 2, 3, 5, 6, 8, 9]
Reversed tuple: (6, 9, 1, 3, 8, 2, 5)
Converted tuple from a list: (10, 20, 30)

Concepts of dictionary:
 A dictionary is a general-purpose data structure used to
store a collection of objects in key-value pairs.
 Each key in the dictionary maps to a single associated
value.
 This data structure is particularly useful when we want
to access values using their corresponding keys, rather
than numerical indices.
 Dictionaries are unordered, which means the items in a

Page 8 of 18
Python Programming
Unit - III

dictionary are not stored in any particular order.


 Dictionaries are mutable, which means they can be changed after they are created.
 Dictionaries can be nested, which means a dictionary can contain another dictionary as a value.

Program:
#Creating a dictionary Output:
Prn_No = {'Prasad':375, 'Rahul': 373} {'Prasad': 375, 'Rahul': 373}
prasad's Prn no is:375
Rahul's Prn no is:373
#printing whole dictionary items
print(Prn_No)

#accessing indivisual items by key in dictionary


print(f"prasad's Prn no is:{Prn_No['Prasad']}")
print(f"Rahul's Prn no is:{Prn_No['Rahul']}")

Key Characteristics of Python Dictionaries:

Key-Value Pairs and Structure:

 Dictionaries store data in key-value pairs.


 Keys are unique identifiers that can be of various
data types, including strings, integers, and tuples.
 Values can be of any data type, such as strings,
integers, lists, and even other dictionaries.

Ordering:

 As of Python version 3.7, dictionaries are ordered.


 This means the items have a defined order, and that order will not change.
 In Python 3.6 and earlier, dictionaries are unordered.
 We can access dictionary items by referring to their keys.

Mutability:

 Dictionaries are mutable, allowing us to change, add, or remove items after the dictionary is created.

Duplicates:
 Dictionaries cannot have two items with the same key.
 If we try to add a duplicate key, the new value will overwrite the existing value.

Length:
 The number of items in a dictionary can be determined using the len( ) function.

Accessing Dictionary Items:

 We can access the value of a dictionary item by using the square bracket notation with the corresponding
key.

Page 9 of 18
Python Programming
Unit - III

Basic built in function in dictionary are:

I. clear( )

 Removes all key-value pairs from the dictionary.


 Returns an empty dictionary.
 Example: my_dict.clear()

II. copy( )

 Returns a shallow copy of the dictionary.


 Example: new_dict = my_dict.copy( )

III. get(key, default)

 Returns the value associated with the specified key.


 If the key is not found, returns the default value (optional parameter) or None if not provided.
 Example: value = my_dict.get("key_name", default_value)

IV. items()

 Returns a dictionary view object containing tuples of key-value pairs.


 The view is dynamic and reflects changes in the dictionary.
 Example: items_view = my_dict.items( )

V. keys( )
 Returns a dictionary view object containing the keys of the dictionary.
 The view is dynamic and reflects changes in the dictionary.
 Example: keys_view = my_dict.keys( )

VI. pop(key, default)

 Removes the key and returns its associated value.


 If the key is not found, returns the default value (optional parameter) or raises a KeyError if not provided.
 Example: value = my_dict.pop("key_name", default_value)

VII. popitem( )

 Removes and returns a tuple representing the last key-value pair added to the dictionary.
 Operates in a Last In First Out (LIFO) manner.
 Example: key, value = my_dict.popitem( )

VIII. setdefault(key, default)

 Returns the value associated with the specified key.


 If the key is not found, adds the key with the specified default value (optional parameter) and returns the
default value.
 Example: value = my_dict.setdefault("key_name", default_value)

IX. update(iterable)

 Updates the dictionary with key-value pairs from another dictionary or an iterable (like a tuple with key-
value pairs).
 Example: my_dict.update(new_items)

Page 10 of 18
Python Programming
Unit - III

X. values()
 Returns a dictionary view object containing all the values in the dictionary.
 The view is dynamic and reflects changes in the dictionary.
 Example: values_view = my_dict.values( )

Program:
Prn_No = {'Prasad': 375, 'Rahul': 373}

# copy()
prn_copy = Prn_No.copy()
print("Copied Dictionary:", prn_copy)

# get(key, default)
value = Prn_No.get('Prasad', -1)
print("Value for 'Prasad':", value)

# items()
items = Prn_No.items()
print("Items:", items)

# keys()
keys = Prn_No.keys()
print("Keys:", keys)

# pop(key, default)
remove = Prn_No.pop('Prasad', -1)
print("Removed Value:", remove)
print("Dictionary after pop():", Prn_No)

# popitem()
remove_item = Prn_No.popitem()
print("Popped Item:", remove_item)
print("Dictionary after popitem():", Prn_No)

# setdefault(key, default)
default = Prn_No.setdefault('Rahul', 0)
print("Default Value for 'Rahul':", default)
default = Prn_No.setdefault('kira', 374)
print("Default Value for 'kira':", default)

# update(iterable)
Prn_No.update({'vickey': 271})
print("Dictionary after update:", Prn_No)

# values()
values = Prn_No.values()
print("Values:", values)

# clear()
Prn_No.clear()
print("Dictionary after clear:", Prn_No)

Output:
Copied Dictionary: {'Prasad': 375, 'Rahul': 373}
Value for 'Prasad': 375
Items: dict_items([('Prasad', 375), ('Rahul', 373)])
Keys: dict_keys(['Prasad', 'Rahul'])

Page 11 of 18
Python Programming
Unit - III

Removed Value: 375


Dictionary after pop(): {'Rahul': 373}
Popped Item: ('Rahul', 373)
Dictionary after popitem(): {}
Default Value for 'Rahul': 0
Default Value for 'kira': 374
Dictionary after update: {'Rahul': 0, 'kira': 374, 'vickey': 271}
Values: dict_values([0, 374, 271])
Dictionary after clear: {}

Sets in Python
 A Python set is the collection of the unordered items. Each element in the set must be unique, immutable, and the
sets remove the duplicate elements. Sets are mutable which means we can modify it after its creation.
 Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot directly
access any element of the set by the index. However, we can print them all together, or we can get the list of
elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also
provides the set() method, which can be used to create the set by the passed sequence.
Example 1: Using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)

Example 2: Using set() method


Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
**Please note that only immutable items are allowed in sets.

# Empty curly braces will create dictionary


set3 = {} <class 'dict'>
<class 'set'>
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))

As shown above, empty set can be created using set function only

Adding items to the set


1. Using add() method
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");

Page 12 of 18
Python Programming
Unit - III

Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
2. Example - 2 Using update() function
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);

Removing items from the set

Python provides the discard() method and remove() method which can be used to remove the items from the set. The
difference between these function, using discard() function if the item does not exist in the set then the set remain
unchanged whereas remove() method will through an error.

1. Example-1 Using discard() method


months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
2. Example-2 Using remove() function
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");

Page 13 of 18
Python Programming
Unit - III

months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)

**discard() doesn’t give error if element does not exist whereas remove() gives error if element does not exist
3. Example-3 Using pop() function

We can also use the pop() method to remove the item. Generally, the pop() method will always remove the last item
but the set is unordered, we can't determine which element will be popped from set. Consider the following example to
remove the item from the set using pop() method.

Months = set(["January","February", "March", "April", "May", "June"])


print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)

Function in Python:
 In Python, functions play a crucial role in structuring code by allowing us to encapsulate logic that can be reused
and called upon as needed.

Here are the different types of functions in Python:

 Built-in Functions:

 Python comes with a set of built-in functions that are always


available for use.
 These functions cover a wide range of tasks, from basic operations like mathematical calculations to more
complex tasks like handling data structures.

Some examples of built-in functions include:

 abs( ): Returns the absolute value of a number.


 len( ): Returns the length (number of elements) of an object.
 print( ): Displays output to the console.
 type( ): Returns the type of an object.
 range( ): Generates a sequence of numbers within a specified range.
 str( ): Converts an object to a string representation.
 max( ): Returns the largest item in an iterable.
 min( ): Returns the smallest item in an iterable.
Program:
# Demonstrating the functions
num = -5

Page 14 of 18
Python Programming
Unit - III

lst = [3, 7, 2, 8, 5]
text = "Hello, world!"

# abs(): Returns the absolute value of a number.


abs_value = abs(num)
print("Absolute value:", abs_value)

# len(): Returns the length (number of elements) of an object.


list_length = len(lst)
print("Length of list:", list_length)

# print(): Displays output to the console.


print("This is a demonstration.")

# type(): Returns the type of an object.


print(type(num))
print(type(lst))
print(type(text))

# range(): Generates a sequence of numbers within a specified range.


num_range = range(1, 6)
print("Range:", list(num_range))

# str(): Converts an object to a string representation.


num_str = str(num)
lst_str = str(lst)
print("Number as string:", num_str)
print("List as string:", lst_str)

# max(): Returns the largest item in an iterable.


maximum = max(lst)
print("Maximum value:", maximum)

# min(): Returns the smallest item in an iterable.


minimum = min(lst)
print("Minimum value:", minimum)

Output:
Absolute value: 5
Length of list: 5
This is a demonstration.
<class 'int'>
<class 'list'>
<class 'str'>
Range: [1, 2, 3, 4, 5]
Number as string: -5
List as string: [3, 7, 2, 8, 5]
Maximum value: 8
Minimum value: 2

User-Defined Functions:
 User-defined functions are created by the programmer to
perform specific tasks.

 These functions allow us to encapsulate a sequence of code


statements under a single name, making our code more organized and
modular.

 To define a user-defined function, we use the def keyword,


followed by the function name, parameters (if any), and a colon.

Page 15 of 18
Python Programming
Unit - III

 The function body is indented below the definition.


Here's an example of a user-defined function:

Example:
# we cannot call a function without definition
# we must define a function before calling it

#Function declaration and definition


def greet():
print("Hello")

#Calling a function
greet()

 Parameterized functions:
 In Python, a parameterized function is a function that takes one or more parameters (also known as arguments)
when it's called.
 Parameters are placeholders for values that the function needs to operate on.
 When the function is invoked(Called) with specific values, these values are passed as arguments and are used
within the function's code.
 There are two types of parameters

 Formal Parameters (Parameters in the Function Definition):


 Formal parameters are placeholders that we define in the function's definition.
 They act as variables within the function's body and represent the values that will be passed to the function
when it's called.
 Formal parameters are placed within the parentheses in the function definition.

 Actual Parameters (Arguments):


 Actual parameters, often referred to as arguments, are the values that are passed into a function when it's called.
 These values are substituted for the corresponding formal parameters in the function's definition.
 Actual parameters provide the specific data that the function works with when it's executed.

Program:
# Program to demonstrate Parameterize function as well as Actual and Formal parameters

def greet(Name): #<------ Formal Parameter


print(f"Hello {Name}")

name = 'Prasad'
Output:
# Function calling by passing arguments
greet(name) # <------ Actual parameter/Arguments Hello Prasad
greet('Mrityunjay') # <------ Actual parameter/Arguments Hello Mrityunjay

Page 16 of 18
Python Programming
Unit - III

 Global Variables:
 Global variables are declared outside of any function and have a global scope, which means
 They can be accessed throughout the program, both inside and outside functions.
 For example, if we declare a variable x outside any function, it becomes a global variable, and its value can be
accessed and modified from anywhere in the program.
 Here's an example:
x = "awesome" #Global Variable

def fun():
print("Python is " + x) #Used x in function

Output:
fun() #Calling a function
Python is awesome
print(f"python is " + x) # Used same x in main program python is awesome

 Local Variables:
 Local variables are declared inside a function and have a scope limited to that function.
 They can only be accessed and used within the function in which they are defined.
 we can have variables with the same name declared both globally and locally.
 When a variable is declared locally within a function, it takes precedence over the global variable with the same
name within that function's scope

Program:
x = "awesome"
Output:
def fun():
Python is fantastic
x = "fantastic" #Local variable with different assignment
Python is awesome
print("Python is " + x)

fun()
print("Python is " + x) #Using x but this is global variable it will take awesome as x definition

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
x = "awesome"
def myfunc():
global x
x = "fantastic"

Page 17 of 18
Python Programming
Unit - III

myfunc()
print("Python is " + x)
******************

Reference: The contents present in the notes have also been taken from WWW (world wide Web
resources) and compiled in the notes.

Note: Students are advised to read the notes carefully and build the concept. And practice In the
perspective approach.

***********************

Page 18 of 18

You might also like