Python m3
Python m3
[BDS306B]
LECTURE NOTES
MODULE -3
2
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
comprehension; Dictionaries: operations and methods, comprehension.
Lists have the following characteristics:
Lists are ordered, meaning that the items have a defined order, and that order will not change unless
we modify the list1.
Lists are changeable, meaning that we can add, remove, or modify items in a list after it has been
created1.
Lists allow duplicate values, meaning that a list can have multiple items with the same value 1.
Lists can contain items of any data type, such as strings, integers, booleans, or even other lists 1.
List:
>>> x=list()
>>> x
[]
3
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
Assuming following input −
L = ['mrcet', 'college', 'MRCET!']
4
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Python Expression Results Description
5
PYTHON PROGRAMMING III YEAR/II SEM MRCET
L[-2] college Negative: count from the right
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
[2, 4, 6, 8]
List methods:
The list data type has some more methods. Here are all of the methods of list objects:
Del()
6
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Append()
Extend()
Insert()
Pop()
Remove()
Reverse()
Sort()
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
>>> del(x)
>>> x # complete list gets deleted
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:
>>> x=[1,2,4,6,7]
7
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x.insert(2,10) #insert(index no, item to be inserted)
>>> x
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> x.pop()
>>> x
[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
8
PYTHON PROGRAMMING III YEAR/II SEM MRCET
[1, 2, 10, 4, 6]
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> x=[10,1,5,3,8,7]
>>> x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
List loop:
Loops are control structures used to repeat a given section of code a certain number of times
or until a particular condition is met.
#list of items
list = ['M','R','C','E','T']
9
PYTHON PROGRAMMING III YEAR/II SEM MRCET
i=1
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/listlooop.py
1
3
5
7
9
Method #3: using while loop
Mutability:
A mutable object can be changed after it is created, and an immutable object can't.
>>> x=[1,2,4,6,7]
11
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x
[1, 2, 10, 4, 6, 7]
>>> x.insert(4,['a',11])
>>> x
Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.
>>> x.pop()
>>> x
[1, 2, 10, 4, 6]
>>> x.pop(2)
10
>>> x
[1, 2, 4, 6]
Remove: The remove() method removes the specified item from a given list.
>>> x=[1,33,2,10,4,6]
>>> x.remove(33)
>>> x
[1, 2, 10, 4, 6]
12
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x.remove(4)
>>> x
[1, 2, 10, 6]
>>> x.sort()
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> x=[10,1,5,3,8,7]
>>> x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
13
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Tuples
A tuple is a collection of ordered and unchangeable elements in Python. It is one of the four built-in
data types in Python used to store collections of data.
1. Tuples are ordered, indexed collections of data. Similar to string indices, the first value in
the tuple will have the index [0], the second value [1], and so on.
2. Tuples can store duplicate values.
3. Once data is assigned to a tuple, the values cannot be changed.
4. Tuples allow you to store several data items in one variable. You can choose to store only
one kind of data in a tuple or mix it up as needed.
Creating Tuple
To create a tuple, we can use round brackets () and separate the elements by commas. For example:
my_tuple = ("apple", "banana", "cherry")
print(my_tuple) # ('apple', 'banana', 'cherry')
We can also create a tuple without using brackets, by just assigning values separated by commas to a
variable. For example:
my_tuple = 1, 2, 3
print(my_tuple) # (1, 2, 3)
To create a tuple with only one element, we need to add a comma after the element, otherwise Python will
not recognize it as a tuple1. For example:
my_tuple = ("apple",)
print(type(my_tuple))
Tuples can contain any data type, such as strings, integers, floats, booleans, lists, or other tuples 1. For
example:
my_tuple = ("abc", 34, True, 40.5, "male")
print(my_tuple) # ('abc', 34, True, 40.5, 'male')
create an empty tuple by putting no values between the brackets
tuple1 = ();
Using the tuple() constructor and passing an iterable object as an argument. For example: my_tuple =
tuple([1, 2, 3, "hello"])
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.
Positive Indexing
Negative 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.
Example 1
tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(3))
print(tuple(7)
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.
15
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example
tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(-2))
print(tuple(-8))
Slicing tuples
Slicing is used to access a range of elements in a tuple. We can represent the slicing
operator in the syntax [start:stop:step].
Moreover, it is not necessary to mention the ‘step’ part. The compiler considers it 1 by
default if we do not mention the step part.
Example 1
In the following example we have used the slice operation to slice a tuple. We also use negative
indexing method to slice a tuple.
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
16
PYTHON PROGRAMMING III YEAR/II SEM MRCET
('b', 'd', 'f', 'h')
('j', 'h')
Example 2
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
Output
('u', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'u')
('l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'l', 'n')
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
>>> x= [4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
17
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
18
PYTHON PROGRAMMING III YEAR/II SEM MRCET
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4
Index (): Searches the tuple for a specified value and returns the position of where it was
found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Concatenate operation on tuples
Concatenation of tuples in python means joining two or more tuples to form a single tuple. The
'+' operator can be used to concatenate texts or add numeric values.
19
PYTHON PROGRAMMING III YEAR/II SEM MRCET
print(result)
Repetition
When it is required to repeat a tuple 'N' times, the '*' operator can be used. The '*'
operator behaves like a multiplication operator.
my_result = ((my_tuple_1, ) * N)
Membership
python's membership operators test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators as explained below
−
Operat Examp
Description
or le
x in y,
here in
results in
a 1 if x is
Evaluates to true if it finds a variable in the
in a
specified sequence and false otherwise.
member
of
sequence
y.
20
PYTHON PROGRAMMING III YEAR/II SEM MRCET
of
sequence
y.
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"
a = 2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one variable at a
time. In here, we have assigned tuple 1 with the college information like college name, year,
etc. and another tuple 2 with the values in it like number (1, 2, 3… 7).
For Example,
mrcet
>>> print(tup2[1:4])
(2, 3, 4)
22
PYTHON PROGRAMMING III YEAR/II SEM MRCET
We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
Run the above code- It gives name mrcet for first tuple while for second tuple it gives
number (2, 3, 4)
A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are
immutable.
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/tupretval.py
mrcet college
20
23
PYTHON PROGRAMMING III YEAR/II SEM MRCET
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)
Set:
set is an unordered collection of unique elements. It is defined using curly braces {} and each
element is separated by a comma.
Creating a set
my_set = {1, 2, 3, 4, 5}
A set can store heterogeneous elements, i.e., a mixture of different data types such as strings, integers,
booleans, etc1. However, a set cannot store mutable elements such as lists, dictionaries, or other sets1. For
example:
Python
>>> x = set()
>>> bool(x)
False
24
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x or 1
A set of integers
int_set = {10, 20, 30, 40, 50}
nameSet.add("Ihechikara")
print(nameSet)
# {'John', 'Ihechikara', 'Doe', 'Jane'}
The add() method is used to add a single element, and the update() method is used
to update multiple components.
25
PYTHON PROGRAMMING III YEAR/II SEM MRCET
# Discard an element
my_set.discard(40)
print(my_set) # Output: {10, 20, 30, 50}
# Remove an element
my_set.remove(60) # KeyError!
# Pop an element
print(my_set.pop())
my_set.clear()
print(my_set) # Output: set()
x = fruits.copy()
print(x)
26
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Dictionaries:
Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}
Characteristics
1. Dictionaries are Unordered : The dictionary elements key-value pairs are not
in ordered form.
2. Dictionary Keys are Case Sensitive : The same key name but with different
case are treated as different keys in Python dictionaries.
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
27
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value. Following is a simple example −
Methods:
Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.
The clear() method in Python is a built-in method that is used to remove all the
elements (key-value pairs) from a dictionary. It essentially empties the dictionary,
leaving it with no key-value pairs.
Python3
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)
In Python, the get() method is a pre-built dictionary function that enables you to
obtain the value linked to a particular key in a dictionary. It is a secure method to
access dictionary values without causing a KeyError if the key isn’t present.
Python3
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(d.get('Name'))
print(d.get('Gender'))
28
PYTHON PROGRAMMING III YEAR/II SEM MRCET
d1.update(d2)
print(d1)
29
PYTHON PROGRAMMING III YEAR/II SEM MRCET
dictionary operations:
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x
Add/change
Remove
Length
Delete
Add/change values: You can change the value of a specific item by referring to its key
name
You can update a dictionary by adding a new entry or a key-value pair, modifying
an existing entry, or deleting an existing entry as shown below in the simple
example −
Live Demo
We use the del statement to remove an element from the dictionary. For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}
print(country_capitals)
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is
a simple example −
Live Demo
print(people)
32
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example 2: Access the elements using the [] syntax
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
del people[3]['married']
del people[4]['married']
print(people[3])
print(people[4])
Using the for loops, we can iterate through each elements in a nested dictionary.
Person ID: 1
Name: John
Age: 27
Sex: Male
Person ID: 2
Name: Marie
34
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Age: 22
Sex: Female
In the above program, the first loop returns all the keys in the nested dictionary people . It
consist of the IDs p_id of each person. We use these IDs to unpack the information p_info of
each person.
The second loop goes through the information of each person. Then, it returns all of the
keys name , age , sex of each person's dictionary.
Now, we print the key of the person’s information and the value for that key.
35