chapter 3 python
chapter 3 python
Prof. K.D.Dongare
Python Programming
Lists
Python Lists are just like dynamically sized arrays, declared in other
languages.
The list is a sequence data type which is used to store the collection of
data.
A single list may contain Data Types like Integers, Strings, as well as
Objects.
Example:
Output:
["Shree", "Krushna"]
#Creating a List
"""# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
b = ['RAJ', 'RAVI', 'RAM']
Prof. K.D.Dongare
Python Programming
Characteristics of Lists
The characteristics of the List are as follows:
Prof. K.D.Dongare
Python Programming
Lists in Python can be created by just placing the sequence inside the
square brackets[].
Example:
# Creating a List
List = [] # Creating a Blanck List
print("Blank List: ")
print(List)
Prof. K.D.Dongare
Python Programming
Output:
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Krushna
Classes
Prof. K.D.Dongare
Python Programming
Example:
Prof. K.D.Dongare
Python Programming
Output:
Ex1
list1=[15,25,3,5.3,"ravi",7249495353,"Abc",0.2]
print(list1)
print(list1[0])
print(list1[5])
print(list1[2:])
print(list1[-1])
print(list1[::-1])
output
15
7249495353
0.2
Prof. K.D.Dongare
Python Programming
EX2
output
element at index 10
EX3
Output
10
50
Prof. K.D.Dongare
Python Programming
Ex4
Output
list element are
at index 0 element is: 10
at index 1 element is: 20
at index 2 element is: 30
at index 3 element is: 40
at index 4 element is: 50
Prof. K.D.Dongare
Python Programming
Slicing of a List
We can get substrings and sub lists using a slice. In Python List, there
are multiple ways to print the whole list with all the elements, but to
print a specific range of elements from the list, we use the Slice
operation.
Slice operation is performed on Lists with the use of a colon(:).
To print elements from beginning to a range use:
[: Index]
a = [1, 2, 3, 4, 5, 7 , 9, 6, 8]
print(a[:4])
[Index:]
a = [1, 2, 3, 4, 5, 7 , 9, 6, 8]
print(a[2:])
To print the whole list in reverse order, use
[::-1]
a = [1, 2, 3, 4, 5, 7 , 9, 6, 8]
rev = a[::-3]
Prof. K.D.Dongare
Python Programming
Append() method only works for the addition of elements at the end of the
List, for the addition of elements at the desired position, insert() method is
used.
Example:
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
Prof. K.D.Dongare
Python Programming
Output:
Initial List:
[1, 2, 3, 4]
Elements can be added to the List by using the built-in append() function.
Only one element at a time can be added to the list by using the append()
method, for the addition of multiple elements with the append() method,
loops are used.
Example:
# Python program to demonstrate Addition of elements in a List
# Creating a List
List = []
print("Initial blank List: ")
print(List)
Prof. K.D.Dongare
Python Programming
Output:
Prof. K.D.DONGARE
Python Programming
Extend: -
This function adds element of parameter list with invoking List
its syntax is:- list1 name .extend(list 2 name)
In Python, extend() method is used to add items from one list to the end of
another list. This method modifies the original list by appending all items from
the given iterable.
Using extend() method is easy and efficient way to merge two lists or add multiple
elements at once.
a = [1, 2, 3]
b = [4, 5]
a.extend(b)
print(a)
Output
[1, 2, 3, 4, 5]
The length of a list refers to the number of elements in the list. There are several
methods to determine the length of a list in Python. In this article, we’ll explore
different methods to find the length of a list. The simplest and most common way
to do this is by using the len() function.
The len() function is the simplest and most efficient way to find the length of a list
in Python. It’s an inbuilt function that can be used on any sequence or collection,
including lists.
a = [1, 2, 3, 4, 5]
length = len(a)
print(length)
Output
5
Prof. K.D.DONGARE
Python Programming
If we want to find the length of list without using any inbuilt function
than we can consider this method
a = [1, 2, 3, 4, 5]
# Initialize a counter to zero
count = 0
# Loop through each element in the list
for val in a:
# Increment the counter for each element
count += 1
print(count)
Using length_hint()
The length_hint() function from the operator module provides an
estimated length (not a guaranteed accurate count) of an iterable. This
method is not typically used in regular code where len() is applicable.
from operator import length_hint
a = [1, 2, 3, 4, 5]
length = length_hint(a)
print(length)
Output
5
Prof. K.D.DONGARE
Python Programming
Prof. K.D.DONGARE
Python Programming
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
list = ["apple", "banana", "cherry"]
list.pop()
print(list)
Output
['apple', 'banana']
The del keyword also removes the specified index:
Ex to Remove the first item:
list = ["apple", "banana", "cherry"]
del list[0]
print(list)
['banana', 'cherry']
The del keyword can also delete the list completely.
Exp. To Delete the entire list:
list = ["apple", "banana", "cherry"]
del list
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
Example to Clear the list content:
list = ["apple", "banana", "cherry"]
list.clear()
print(list)
Prof. K.D.DONGARE
Python Programming
Python IN Operator
The in operator is used to check if a character/substring/element exists
in a sequence or not. Evaluate to True if it finds the specified element in a
sequence otherwise False.
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
# using membership 'in' operator
# checking an integer in a list
print(2 in list1)
# checking a character in a string
print('O' in str1)
# checking for a key in a dictionary
print(3 in dict1)
Output
Prof. K.D.DONGARE
Python Programming
True
False
True
operators.contains() Method
Prof. K.D.DONGARE
Python Programming
Output
True
False
True
True
True
The is not operator evaluates True if both variables on the either side of
the operator are not the same object in the memory location otherwise it
evaluates False.
# Python program to illustrate the use # of 'is' identity operator
num1 = 5
num2 = 5
a = [1, 2, 3]
b = [1, 2, 3]
c=a
s1 = "hello world"
s2 = "hello world"
# using 'is not' identity operator on different datatypes
print(num1 is not num2)
print(a is not b)
print(a is not c)
print(s1 is not s2)
print(s1 is not s1)
Output
False
True
False
False
False
Prof. K.D.DONGARE
Python Programming
Tuples
Example:
Prof. K.D.DONGARE
Python Programming
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Using square brackets we can get the values from tuples in Python.
Prof. K.D.DONGARE
Python Programming
Example:
Output:
In the above methods, we use the positive index to access the value in
Python, and here we will use the negative index within [].
Example:
var = (1, 2, 3)
print("Value in Var[-1] = ", var[-1])
print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-3])
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] =
1
Prof. K.D.DONGARE
Python Programming
Tuples in a loop
Output:
((' Krushna',),)
(((' Krushna',),),)
((((' Krushna',),),),)
(((((' Krushna',),),),),)
((((((' Krushna',),),),),),)
Advantages of Tuples
Tuples take less time than lists do.
Due to tuples, the code is protected from accidental modifications. It is
desirable to store non-changing information in "tuples" instead of
"records" if a program expects it.
Prof. K.D.DONGARE
Python Programming
Syntax
slice(start, end, step)
Parameter Values
Paramete Description
r
Prof. K.D.DONGARE
Python Programming
Indexing Tuples
In Python, every tuple with elements has a position or index. Each element
of the tuple can be accessed or manipulated by using the index number.
They are two types of indexing −
Positive Indexing
Negative Indexing
Positive Indexing
In positive the first element of the tuple is at an index of 0 and the following
elements are at +1 and as follows.
In the below figure, we can see how an element in the tuple is associated with
its index or position.
Ex pf positive indexing
tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(3))
print(tuple(7))
Output
The above code produces the following results
7
4
Prof. K.D.DONGARE
Python Programming
Negative Indexing
In negative indexing, the indexing of elements starts from the end of the
tuple. That is the last element of the tuple is said to be at a position at -1 and
the previous element at -2 and goes on till the first element.
In the below figure, we can see how an element is associated with its index or
position of a tuple.
Output
The above code produces the following results
4
2
Create a tuple and a slice object. Use the slice object to get only the two first items of the
tuple:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])
output
('a', 'b')
Create a tuple and a slice object. Start the slice object at position 3, and slice to position 5,
and return the result:
Prof. K.D.DONGARE
Python Programming
output
('d', 'e')
Create a tuple and a slice object. Use the step parameter to return every third item:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(0, 8, 3)
print(a[x])
Output
('a', 'd', 'g')
Ex.
tuple= ('a','b','c','d','e','f','g','h','i','j')
print(tuple[0:6])
print(tuple[1:9:2])
print(tuple[-1:-5:-2])
Output
The above code produces the following results
('a', 'b', 'c', 'd', 'e', 'f')
('b', 'd', 'f', 'h')
('j', 'h')
Prof. K.D.DONGARE
Python Programming
In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently.
Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or
steps within the list of tuples. This technique is particularly handy when dealing with
datasets or organizing information.
Basic Slicing
In this example, the below code initializes a list of tuples and then extracts a sub list
containing tuples at index 1 and 2 (inclusive) using slicing.
The result is `sliced` containing `[(2, 'banana'), (3, 'orange')]`, which is then printed.
# Initialize list of tuples
tuples = [(1, 'apple'), (2, 'banana'), (3, 'orange'), (4, 'grape')]
Output
[(2, 'banana'), (3, 'orange')]
Slice A List Of Tuples In Python Using Negative Indices
In this example, below code initializes a list of tuples and then extracts a sublist
containing tuples from the third last to the second last position using negative indexing.
The result is `sliced_list` containing `[(2, 'banana'), (3, 'orange')]`, which is then printed.
# Initialize list of tuples
tuples = [(1, 'apple'), (2, 'banana'), (3, 'orange'), (4, 'grape')]
Prof. K.D.DONGARE
Python Programming
sliced = tuples[-3:-1]
# Display list oftuples
print(sliced)
Output
[(2, 'banana'), (3, 'orange')]
Ex.
my_tuple = ('t', 'u', 'r', 'i', 'a', 'l', 's', 'p','o', 'i', 'n', 't')
print(my_tuple[1:]) #Print elements from index 1 to end
print(my_tuple[:2]) #Print elements from start to index 2
print(my_tuple[5:12]) #Print elements from index 1 to index 3
print(my_tuple[::5]) #Print elements from start to end using step size
print(my_tuple[::-1]) #Print elements from end to start (reverse)
Output
('u', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'u')
('l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'l', 'n')
('t', 'n', 'i', 'o', 'p', 's', 'l', 'a', 'i', 'r', 'u', 't')
Prof. K.D.DONGARE
Python Programming
# Using String
tup = ('Geeks', 'For')
print(tup)
# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))
Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Prof. K.D.DONGARE
Python Programming
Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
Prof. K.D.DONGARE
Python Programming
((((('Geeks',),),),),)
Accessing of Tuples
We can access the elements of a tuple 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.
Example:
# Accessing Tuple with Indexing
tup = tuple("Geeks")
print(tup[0])
# Tuple unpacking
tup = ("Geeks", "For", "Geeks")
Output
G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks
Prof. K.D.DONGARE
Python Programming
Concatenation of Tuples
Tuples can be concatenated using the + operator. This operation combines two or more
tuples to create a new tuple.
Note- Only the same datatypes can be combined with concatenation, an error arises if a
list and a tuple are combined.
tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')
Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Prof. K.D.DONGARE
Python Programming
Slicing of Tuple
Slicing a tuple means creating a new tuple from a subset of elements of the original tuple.
The slicing syntax is tuple[start:stop:step].
Note- Negative Increment values can also be used to reverse the sequence of Tuples.
Output
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
('S', 'F', 'O', 'R', 'G')
Prof. K.D.DONGARE
Python Programming
Deleting a Tuple
Since tuples are immutable, we cannot delete individual elements of a tuple. However,
we can delete an entire tuple using del statement.
Note- Printing of Tuple after deletion results in an Error.
# Deleting a Tuple
tup = (0, 1, 2, 3, 4)
del tup
print(tup)
output
display error
Output
3
Concatenate tuples
we add two tuples and return the concatenated tuple
step-by-step approach :
1. Initialize two tuples with elements (1, 3, 5) and (4, 6) respectively and assign them
to the variables test_tup1 and test_tup2.
2. Print the original values of the two tuples using print() function and concatenate
them with the string using + operator.
3. Concatenate the two tuples test_tup1 and test_tup2 using + operator and assign
the result to a new variable res.
4. Print the concatenated tuple res using print() function and concatenate it with the
string using + operator.
5. End of the program.
Prof. K.D.DONGARE
Python Programming
# initialize tuples
tup1 = (1, 3, 5)
tup2 = (4, 6)
# printing result
print("The tuple after concatenation is : ", res)
output
The original tuple 1 : (1, 3, 5)
The original tuple 2 : (4, 6)
The tuple after concatenation is : (1, 3, 5, 4, 6)
Built-in-Method Description
Find in the tuple and returns the index of the given value where it’s
index( )
available
Prof. K.D.DONGARE
Python Programming
return true if any element of the tuple is true. if tuple is empty, return
any() false
sorted() input elements in the tuple and return a new sorted list
Tuples VS Lists
Similarities Differences
Methods that can be used for both lists and we generally use ‘tuples’ for
tuples: heterogeneous (different) data types
and ‘lists’ for homogeneous (similar)
count(), Index() data types.
Lists can be stored in tuples. ‘Lists’ are mutable whereas ‘tuples’ are
Prof. K.D.DONGARE
Python Programming
Similarities Differences
immutable.
Prof. K.D.DONGARE
Python Programming
Set
Sets in Python
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.
Internally use hashing that makes set efficient for search, insert and delete
operations. It gives a major advantage over a list for problems with these
operations.
Mutable, meaning we can add or remove elements after their creation, the
individual elements within the set cannot be changed directly.
Sets Operations :
Adding Elements
Removing Elements
To remove elements from a set, you can use the remove() method. It will raise a
KeyError if the element is not present in the set. Alternatively, you can use the
discard() method, which won’t raise an error if the element is not found:
fruits.remove("banana")
fruits.discard("watermelon")
Ex. Demonstrate union operation
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C = {1, 2, 3}
Prof. K.D.DONGARE
Python Programming
print('A U B =', A| B)
print('B U C =', B | C)
print('A U B U C =', A | B | C)
Output
A U B = {2, 'a', 'd', 'c'}
B U C = {1, 2, 3, 'd', 'c'}
A U B U C = {1, 2, 3, 'd', 'c', 'a'}
Note that even after UNION operation , resulting set-c will not contain duplicate element
Set intersection
The intersection() method returns a new set with elements that are common to all sets.
Example
A = {2, 3, 5}
B = {1, 3, 5}
Output: {3, 5}
print(s)
Output
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Python sets cannot have duplicate values. While you cannot modify the individual
elements directly, you can still add or remove elements from the set.
# a set cannot have duplicate values
# and we cannot change its items
The first code explains that the set cannot have a duplicate value. Every item in it is a
unique value.
The second code generates an error because we cannot assign or change a value once the
set is created. We can only add or delete items in the set.
Set Operation
Sets support various operations that are common in mathematics.
These include:
Prof. K.D.DONGARE
Python Programming
Union: union() or |
Intersection: intersection() or &
Difference: difference() or –
Symmetric Difference: symmetric_difference() or ^
Subset: issubset()
Superset: issuperset()
Here’s an example demonstrating some of these operations:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# Union
union_set = set1.union(set2)
# Intersection
intersection_set = set1.intersection(set2)
# Difference
difference_set = set1.difference(set2)
# Symmetric Difference
symmetric_difference_set = set1.symmetric_difference(set2)
# Subset
is_subset = set1.issubset(set2)
# Superset
is_superset = set1.issuperset(set2)
# A Python program to
# demonstrate adding elements
# in a set
# Creating a Set
student = {"Jay", "Idrish", "Archi"}
Prof. K.D.DONGARE
Python Programming
print("People:", student)
student.add("Daxit")
print("People:", student)
x.update(y)
print(x)
Output
{'microsoft', 'apple', 'banana', 'cherry', 'google'}
Ex.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.update(y)
print(x)
Prof. K.D.DONGARE
Python Programming
x.update ([4,5],{3,5,6})
print(x)
x.update (["ajay",5],{"vir",5,6})
print(x)
set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)
# This method will remove all the elements of the set
set1.clear()
Output
Initial set
{1, 2, 3, 4, 5, 6}
Prof. K.D.DONGARE
Python Programming
Output
Union using union() function
{'Idrish', 'Arjun', 'Jay', 'Karan', 'Archil'}
Prof. K.D.DONGARE
Python Programming
The union of two sets A and B includes all the elements of sets A and B.
We use the | operator or the union() method to perform the set union operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
Prof. K.D.DONGARE
Python Programming
Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
In Python, we use the & operator or the intersection() method to perform the set intersection operation. For
example,
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
Output
Prof. K.D.DONGARE
Python Programming
Intersection using intersection(): {1, 3}
The difference between two sets A and B include elements of set A that are not present on set B.
We use the - operator or the difference() method to perform the difference between two sets. For example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
Output
Prof. K.D.DONGARE
Python Programming
The symmetric difference between two sets A and B includes all elements of A and B without the common elements.
In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric differences between
two sets. For example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
print('using ^:', A ^ B)
# using symmetric_difference()
Output
using ^: {1, 3, 5, 6}
Prof. K.D.DONGARE
Python Programming
We can use the == operator to check whether two sets are equal or not. For example,
# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}
if A == B:
else:
Prof. K.D.DONGARE
Python Programming
Prof. K.D.DONGARE
Python Programming
Method Description
Python Dictionary
A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists and tuples,
each item in a dictionary is a key-value pair (consisting of a key and a value).
Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {}, separated by commas. For example,
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}
The country_capitals dictionary has three elements (key-value pairs), where 'Germany' is the key and 'Berlin' is the
value assigned to it and so on.
Prof. K.D.DONGARE
Python Programming
print(country_capitals)
Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'Italy': 'Rome'}
print(country_capitals)
Output
{'Canada': 'Ottawa'}
If we need to remove all items from a dictionary at once, we can use the clear() method.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}
print(country_capitals)
Output
{}
Prof. K.D.DONGARE
Python Programming
print(country_capitals)
Output
{'Germany': 'Berlin', 'Italy': 'Rome', 'England': 'London'}
print()
Output
United States
Italy
Washington D.C.
Rome
Prof. K.D.DONGARE
Python Programming
countries = {}
Prof. K.D.DONGARE
Python Programming
Function Description
Prof. K.D.DONGARE