Unit II
Unit II
Unit II
Unit - III
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.
var_name = [value1,value2,value3]
Li = ['prasad',True,10,15.4598]
var_name = (value1,value2,value3)
tup = ('prasad',True,10,15.4598)
set = {value1,value2,value3}
Page 1 of 18
Python Programming
Unit - III
set = {'prasad',10,10.56,True}
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
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)
# extend(): Adds elements from another list or iterable to the end of the current list.
li.extend([7, 9])
print("After extend():", li)
Page 4 of 18
Python Programming
Unit - III
Output:
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:
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
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:
#2. Immutable:
Program:
tpl1 = (10,20,50,-50,80,100)
Output:
Page 6 of 18
Python Programming
Unit - III
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)
Page 7 of 18
Python Programming
Unit - III
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
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)
Ordering:
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.
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
I. clear( )
II. copy( )
IV. 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( )
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( )
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
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)
As shown above, empty set can be created using set function only
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);
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.
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.
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.
Built-in Functions:
Page 14 of 18
Python Programming
Unit - III
lst = [3, 7, 2, 8, 5]
text = "Hello, world!"
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.
Page 15 of 18
Python Programming
Unit - III
Example:
# we cannot call a function without definition
# we must define a function before calling it
#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
Program:
# Program to demonstrate Parameterize function as well as Actual and Formal parameters
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
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