Pyrhon 3rd Chapter
Pyrhon 3rd Chapter
3.1 Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
3. Functionality: The list data type comes with several functions that allow the user to easily
perform different set of operations instead of writing long code from scratch. You can use
dir(list_name) to get a list of all functions provided by a list.
4. Heterogeneous: One of the biggest advantages of using a list is that we can create a list of
heterogeneous elements. We can store the elements of different data types in a single list.
The elements of the different types consume memory according to the value of a particular
type stored in the list.
5. Multidimensional: We can use the list as a multidimensional data structure. With the help
of the multidimensional list, we can easily create a matrix using the list, and we can
perform different matrix operations on the list.
6. Dynamic: The list data type is dynamic in nature. This means that for using a list, we do
not need to declare the size of the list. The list consumes memory according to the
requirement. The list automatically expands when the user inputs data at run time and it
shrinks automatically when the user deletes the data at run time.
7. Easy to insert values: It is very easy to insert values in the list. Lists provide different
methods like append, insert, and extend to add elements to the list. We can take the input
from the user by the input method and using one of these methods, we can enter the
inputted values to the list.
8. Easy to display values: It is very easy to display different values stored in the list. We can
even display the values of the list without iterating over the list. To print the list in a
simple manner, we simply need to write the print statement and to pass the list object to
the print function, which we want to display.
9. Easy to use: The list data type is easy to use as compared to the other data types. It has the
ability to take the memory dynamically and offers different functions to provide an easy
way to write the code.
# empty list
my_list1 = []
# list of integers
my_list2 = [1, 2, 3]
# list with mixed data types
my_list3 = [1, "Hello", 3.4]
# nested list
my_list4 = ["mouse", [8, 4, 6], ['a']]
Output:
Enter the number of elements:5
Enter Value:1
Entered List is: [1]
Enter Value:2
Entered List is: [1, 2]
Enter Value:4
Entered List is: [1, 2, 4]
Enter Value:6
Entered List is: [1, 2, 4, 6]
Enter Value:8
Entered List is: [1, 2, 4, 6, 8]
Output:
Enter Values:1 3 5 2
Entered list is: [1, 3, 5, 2]
Example 2:
list_fruit = ["Apple","Mango","Banana","Avocado"]
first_letters = [ fruits[0] for fruits in list_fruit ]
print(first_letters)
Output:
[‘A’, ‘M’, ‘B’, ‘A’]
Suppose you want to create a list with squares of all whole numbers. Although there exists
various programming approaches for this problem but here is a one line method in python.
We will be introducing something new, so it can get a little tricky.
>>> myQuickList = [x**2 for x in range(5)]
The final list will contain elements like [0, 1, 4, 9, 16], i.e. x**2 where x is varying
from 0 to (5-1).
List Indices
The second list of numbers will print out. In order to access those lower elements, you need
to use a second set of square brackets. In the first set of square brackets, specifies the top
level element that you want to access.
In the example below, that is the first list. Then, in the second set of brackets, specifies the
element within that initial top level element that you want. In that same example, it's the
second element, or the number "4."
number_sets = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(number_sets[0][1])
Output:
Enter the ending range of the list:5
Values in the list are: [0, 1, 2, 3, 4]
>>>print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>print(l.pop(3))
4
>>>print(l)
[1, 2, 3, 5, 6, 7, 8, 9]
You can use negative values to specify the position from the end. The index at the end
is -1.
>>>print(l.pop(-2))
8
>>>print(l)
[1, 2, 3, 5, 6, 7, 9]
>>>print(l)
[1, 2, 3, 5, 6, 7]
>>>l.remove('d')
>>>print(l)
['a', 'b', 'c', 'e', 'f', 'g']
>>>del l[0]
>>>print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>del l[-1]
>>>print(l)
[1, 2, 3, 4, 5, 6, 7, 8]
>>>del l[6]
>>>print(l)
[1, 2, 3, 4, 5, 6, 8]
>>>del l[2:5]
>>>print(l)
[0, 1, 5, 6, 7, 8, 9]
1. append():
The append() method adds an element to the end of a list. We can insert single item in
the list data item with append().
Example:
>>> list[10, 20, 30]
>>> list1.append(40)
>>> list1
[10, 20, 30, 40]
2. extend():
The extend() method extends a list by appending items. We can add several items
using extend() method.
Example:
>>> list1[10, 20, 30, 40]
>>> list1.extend([50, 60])
>>>list1
[10, 20, 30, 40, 50, 60]
3. insert(int, item):
This function is used to insert values, anywhere in the list. The first argument of the list
takes the index where the items will be inserted and second is the value that has to be
inserted.
Example:
>>> myList = ['Python', 'C++', 'Java', 'Ruby', 'Perl']
>>> myList.insert(1, 'JavaScript')
>>> print myList
['Python', 'JavaScript', 'C++', 'Java', 'Ruby', 'Perl']
>>> list1
[10, 20, 30]
>>> list1.insert(1,[15, 25])
[10,[15, 25], 20, 30]
Example:
Output:
Original List:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'G', 'R', 'A', 'M', 'S']
Slicing elements in a range 3-8:
['H', 'O', 'N', 'P', 'R']
Printing sliced elements from 5th index till the end:
['N', 'P', 'R', 'O', 'G', 'R', 'A', 'M', 'S']
Printing all elements:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'G', 'R', 'A', 'M', 'S']
Printing sliced elements upto -5 index:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O']
Printing sliced elements upto 5th index
['P', 'Y', 'T', 'H', 'O']
Printing list elements in reverse order
['S', 'M', 'A', 'R', 'G', 'O', 'R', 'P', 'N', 'O', 'H', 'T', 'Y', 'P']
Printing list elements with step size 2
['P', 'T', 'O', 'P', 'O', 'R', 'M']
Output:
Enter the elements of list: 2 3 4 5
How many times you want to repeat the list 4
[2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5]
Example:
l1=[10,20,30]
l2=[40,50,60]
print("List after concatenation is:",l1+l2)
Output:
List after concatenation is: [10, 20, 30, 40, 50, 60]
Example:
Output:
Enter elements of the list:1 2 3 4 5
Enter the element you want to check the membership3
Result of in operator
Element found in list? True or False: True
Result of not in operator
Element not found in list? True or False? False
list = [1, 3, 5, 7, 9]
# getting length of list
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])
Output:
1
3
5
7
9
Output:
1 3 5 7 9
list = [1, 3, 5, 7, 9]
# Using list comprehension
[print(i,end=" ") for i in list]
Output:
1 3 5 7 9
3.2 Tuples
A Python tuple is a sequence of data values called items or elements. A tuple is a linear data
structure which means that the elements are stored in a linear order one after another. A tuple
is an immutable data type which means a tuple once created cannot be altered. In other
words, a tuple works in a similar fashion as a list but the tuples cannot be updated while lists
can be updated. This restricts the number of operations that can be performed on the tuples.
The tuple data structure is used only when we do not want to update the values of the tuple. If
we want to update the values of the tuple, the only method to do so is to create a new tuple
object as if we try to update the existing tuple, it will raise an error. Likewise a list, a tuple is
a collection of logically related variables of different data types. This means a list is a
collection of heterogeneous data items that one can store values of different types in it.
In Python, a tuple is used to handle a large amount of heterogeneous data, without the need to
declare many individual variables of different types. The elements of the tuples are stored in
the contiguous memory locations, i.e., one after another. Tuple elements can be of any
primitive data types or any sequence data types or a combination of both. A Python tuple can
have any number of elements or items. The main restriction on a tuple is that we cannot
change the value of the existing tuple.
Speed: Since tuples are immutable, iterating through tuples is faster than with lists. So,
there is a slight performance boost.
>>> percentages=(99,95,90,89,93,96)
>>> a,b,c,d,e,f=percentages
>>> c
90
>>> languages=('Python', 'Java')
>>> (a,b)=languages
>>> a
Python
Problem solved. And as we saw in tuple packing, we can skip the parentheses here.
>>> a=1,
>>> type(a)
<class ‘tuple’>
Accessing all the elements from a particular tuple at once allows the user to access all
the values from the tuple only by writing tuple name in print() statement.
>>> print(tup3)
(1,2,3,4,5,6)
If we want to remove specific elements from a tuple then Python does not provide any
explicit statement but we can use index slicing to leave out a particular index.
>>> t1=(10, 20, 30, 40, 50)
>>> t2=t1[:2] + t1[3:]
>>> print(t2)
(10, 20, 40, 50)
We can convert tuple into a list, then remove the item and convert back to a tuple.
>>> t1=(10, 20, 30, 40, 50)
>>> l1=list(t1)
>>> del l1[2]
>>> t2=tuple(l1)
>>> print(t2)
(10, 20, 40, 50)
If the element of tuple is itself a mutable data type like list, its nested items can be
changed as shown:
>>> t1 = (10, 20, 30, [40, 50])
>>> t1[3][0] = 11
>>> t1[3][1] = 12
>>> print(t1)
(10, 20, 30, [11, 12])
We can convert tuple into a list, then update the item and convert back to a tuple.
>>> t1 = (10, 20, 30, 40, 50)
>>> l1 = list(t1)
>>> l1[2] = 60
>>> t2 = tuple(l1)
>>> print(t2)
(10, 20, 60, 40, 50)
t=(1,2,3,4,5,6,7,8)
print("Value from index 1 to 4:",t[1:5])
print("Value from index 1 to end:",t[1:])
print("Value from starting to 4:",t[:5])
print("Value from alternate index from starting till end:",t[::2])
print("Value from alternate index starting from 2 till 6:",t[2:7:2])
Output:
Value from index 1 to 4: (2, 3, 4, 5)
Value from index 1 to end: (2, 3, 4, 5, 6, 7, 8)
Value from starting to 4: (1, 2, 3, 4, 5)
Value from alternate index from starting till end: (1, 3, 5, 7)
Value from alternate index starting from 2 till 6: (3, 5, 7)
Output:
Enter elements of tuple:2 3 4 5
How many times you want to repeat the elements of the tuple:3
Elements after repeating are: (2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5)
t1=(10,20)
t2=(39,40)
print("Tuples after concatenation operation is: ",t1+t2)
Output:
t=(1,5,46,3,9)
print("Result of in operator")
print("Element 3 found in tuple true or false?",3 in t)
print("Result of not in operator")
print("Element 3 not found in tuple true or false?",3 not in t)
Output:
Result of in operator
Element 3 found in tuple true or false? True
Result of not in operator
Element 3 not found in tuple true or false? False
t=(1,5,46,3,9)
print("Tuple before updating is: ",t)
t1=()
t1=t[:1]+(8,)+t[1:]
print("Tuple after updating at index 1 is: ",t1)
Output:
Tuple before updating is: (1, 5, 46, 3, 9)
Tuple after updating at index 1 is: (1, 8, 5, 46, 3, 9)
Output:
1 2 3 4 5
Methods of Tuple:
Sr.
Method Description Example
No.
>>> t1
Returns the number of
(1, 2, 3, 2, 5)
1 count() times a specified value
>>> t1.count(2)
occurs in a tuple.
2
Searches the tuple for a >>> t1
specified value and (1, 2, 3, 4, 5)
2 index()
returns the position where >>> t1.index(4)
it was found 3
3.3 Sets
A Set in Python is mutable, iterable, and does not have any duplicate elements. It is an
unordered collection of elements which means that a set is a collection that stores elements
of different Python Data Types. Remember that a set in Python doesn’t index the elements in
a particular order. Let us look at some of the properties of sets in Python. Sets in Python are
usually used to perform some mathematical functions such as union, intersection, difference
and complement etc.
In Python sets, elements don’t have a specific order.
Sets in Python can’t have duplicates. Each item is unique.
The elements of a set in Python are immutable. They can’t accept changes once added.
But, don’t get confused with the fact that sets in Python are mutable. Python sets allow
addition and deletion operations.
A set doesn't store duplicate objects. Even if an object is added more than once inside the
curly brackets, only one copy is held in the set object. Hence, indexing and slicing operations
cannot be done on a set object.
>>> S1={1, 2, 2, 3, 4, 4, 5, 5}
>>> S1
{1, 2, 3, 4, 5}
set() function
Python has an in-built function set() using which a set object can be constructed out of any
sequence such as a string, list or a tuple object.
>>> s1=set("Python")
>>> s1
{'t', 'h', 'o', 'n', 'P', 'y'}
>>> s2=set([45,67,87,36, 55])
>>> s2
{67, 36, 45, 87, 55}
>>> s3=set((10,25,15))
>>> s3
The order of elements in the set is not necessarily the same as the order given at the time of
assignment. Python optimizes the structure of a set for performing operations over it, as
defined in mathematics.
Only immutable (and hashable) objects can be a part of a set object. Numbers (integer, float,
as well as complex), strings, and tuple objects are accepted, but list and dictionary objects are
not.
>>> S1={(10,10), 10,20}
>>> S1
{10, 20, (10, 10)}
>>> S2={[10,10], 10,20}
TypeError: unhashable type: 'list'
In the above example, (10,10) is a tuple, hence it becomes part of the set. However, [10,10] is
a list, hence an error message is displayed saying that the list is unhashable. (Hashing is a
mechanism in computer science which enables quicker search of objects in the computer's
memory.)
Note: Even though mutable objects are not stored in a set, the set itself is a mutable object.
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday',
'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
1. discard() :
This method takes the item to delete as an argument.
>>> numbers.discard(3)
>>> numbers
{1, 2, 4, 5, 6}
As you can see in the resulting set, the item 3 has been removed.
2. remove() :
Like the discard() method, remove() deletes an item from the set.
>>> numbers.remove(5)
>>> numbers
{1, 2, 4, 6}
discard() vs remove()-
These two methods may appear the same to you, but there’s actually a difference. If you
try deleting an item that doesn’t exist in the set, discard() ignores it, but remove()
raises a KeyError.
>>> numbers.discard(7)
>>> numbers
{1, 2, 4, 6}
>>> numbers.remove(7)
Traceback (most recent call last):
File “<pyshell#37>”, line 1, in <module>
numbers.remove(7)
KeyError: 7
3. pop() :
Like on a dictionary, you can call the pop() method on a set. However, here, it does not
take an argument. Because a set doesn’t support indexing, there is absolutely no way to
pass an index to the pop method. Hence, it pops out an arbitrary item. Furthermore, it
prints out the item that was popped.
>>> numbers.pop()
1
4. clear() :
Like the pop() method, the clear() method for a dictionary can be applied to a Python
set as well. It empties the set in Python.
>>> numbers.clear()
>>> numbers
set()
1. Add() :
It takes as argument the item to be added to the set.
>>> numbers={3,1,2,4,6,5}
>>> numbers.add(3.5)
>>> numbers
{1, 2, 3, 4, 5, 6, 3.5}
If you add an existing item in the set, the set remains unaffected.
>>> numbers.add(4)
>>> numbers
{1, 2, 3, 4, 5, 6, 3.5}
2. update() :
This method can add multiple items to the set at once, which it takes as arguments.
>>> numbers.update([7,8],{1,2,9})
>>> numbers
{1, 2, 3, 4, 5, 6, 3.5, 7, 8, 9}
As is visible, we could provide a list, set, strings, and tuples as arguments to this. This is
because this is different than creating a set.
operators has a corresponding method associated with the built-in set class like union(),
intersection(), difference(), symmetric_difference().
1. Union:
This method performs the union operation on two or more Python sets. What it does is it
returns all the items that are in any of those sets.
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1|s2
{1, 2, 3, 4, 5, 6, 7, 8}
>>> s2.union(s1)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set1.union(set2,set3)
{1, 2, 3, 4, 5, 6, 7}
2. Intersection:
This method takes as argument sets, and returns the common items in all the sets.
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1&s2
{4, 5}
>>> s1.intersection(s2)
{4, 5}
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set2.intersection(set1,set3)
set()
It returned an empty set because these three sets have nothing in common.
3. Difference:
The difference operation returns the difference of two or more sets. It returns as a set.
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1-s2
{1, 2, 3}
>>> s2-s1
{8, 6, 7}
>>> s1.difference(s2)
{1, 2, 3}
>>> s2.difference(s1)
{8, 6, 7}
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set1.difference(set2,set3)
{1, 2}
4. Symmetric Difference:
The result of symmetric difference is a set consisting of elements in both sets, excluding
the common elements.
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1^s2
{1, 2, 3, 6, 7, 8}
>>> s2^s1
{1, 2, 3, 6, 7, 8}
>>> s1.symmetric_difference(s2)
{1, 2, 3, 6, 7, 8}
>>> s2.symmetric_difference(s1)
{1, 2, 3, 6, 7, 8}
Membership
We can apply the ‘in’ and ‘not in’ python operators on items for a set. This tells us
whether they belong to the set.
>>> 'p' in {'a','p','p','l','e'}
True
Methods of Sets:
We have already discussed the methods on set like union(), intersection(),
difference(), symmetric_difference(), add(), discard(), remove(),
pop(), update(). Remaining methods on set are:
Sr.
Method Description Example
No.
>>> set1={1,2,3}
As we discussed in >>> set2={3,4,5}
intersection(), it does not >>>
1 intersection_update() update the set on which it is set1.intersection_updat
called. For this, we have the e(set2)
intersection_update() method. >>> set1
{3}
>>> set1={1,2,3}
>>> set2={3,4,5}
Like intersection-update(),
>>>
this method updates the
2 difference_update() set1.difference_update(
Python set with the
set2)
difference.
>>> set1
{1,2}
>>> set1={1,2,3}
Like the two methods we >>> set2={3,4,5}
discussed before this, it >>>
symmetric_difference_
3 updates the set on which it is set1.symmetric_differen
update()
called with the symmetric ce_update(set2)
difference. >>> set1
{1, 2, 4, 5}
>>> max(a)
The copy() method creates a 6>>> set4=set1.copy()
4 copy() shallow copy of the Python >>> set1,set4
set. ({1, 2, 4, 5}, {1, 2,
4, 5})
>>>
This method returns True if
{1,3,2}.isdisjoint({4,5
5 isdisjoint() two sets have a null
,6})
intersection.
True
This method returns true if >>>
6 issubset() the set in the argument {1,2}.issubset({1,2,3})
contains this set. True
Like the issubset() method, >>>
this one returns True if the set {1,3,4}.issuperset({1,2
7 issuperset()
contains the set in the })
argument. False
3.4 Dictionaries
The Python Dictionary is a sequence of data values called items or elements. A dictionary is
an associative data structure, which means that elements are stored in a non-linear fashion.
In Python, a list or tuple is referred to as a linear data structure in which the elements are
stored one after other, i.e., the first element, then the second element, then the third, and so
on. The linear data structure is required when the elements need to be accessed in a sequential
order or one after another or when someone simply needs to access the elements directly by
indexes. In the associative data structure, the elements are not stored in the sequence entered
by the user, so each element is associated with a key. The elements are accessed using keys.
The dictionary data structure represents a group of elements arranged in the form of key-
value pairs. The values of the dictionary are accessed by keys easily, so we do not need to
bother about the order in which the elements are stored. The dictionary data type is a flexible
data type that can be modified according to the requirement, which makes it a mutable data
type. This means we can update the already existing dictionary and there is no need to create
a new dictionary object. The Python dictionary is similar to that of a list. The main difference
is that a dictionary contains the elements in key-value pairs. The dictionary is a collection of
heterogeneous data items. One can store values of different types in it. The values in the
dictionary are mutable in nature and the keys are immutable in nature. We can modify the
value associated with the key, but there is no way to change the keys of a particular value. A
tuple can easily become the keys for the dictionary while a list can easily become the values
of the dictionary. Moreover, a dictionary can dynamically expand or shrink when elements
are added to or removed from it. In Python, the dictionary is used to handle a large amount of
heterogeneous data, without the need to declare many individual variables of different types.
The elements of the dictionary are not stored in the order entered by the user. Dictionary keys
and values can be of various types such as integer, float, or string types. The Python
dictionary can have any number of elements or items. The keys in the dictionary do not
contain the same value for different elements whereas values in the dictionary may contain
the same values for different elements. If we try to insert the value with the same key, the
newly inserted values replace the old value associated with that key. The following table
shows the representation of a dictionary:
Keys Values
Marks 69.5
Roll No. 54
Name Nilesh
Phone 9898989898
5 691.4
Each dictionary value is accessed and manipulated using a dictionary name followed by a
unique key in square brackets associated with the particular value. In the preceding table,
Marks key is associated with value 69.5, Roll No. key is associated with value 54, Name key
is associated with the value Nilesh, Phone key is associated with the value 9898989898, and
the key 5 is associated with the value 691.44.
10. Associative data structure: The dictionary data type is associative in nature. If we want
to get any value stored in the dictionary, we need to refer to the key associated with the
value. This is used when the location of the values stored in the sequence is not required
to access in a linear fashion.
dict() Function:
Python provides built-in function dict() for creating a dictionary.
>>> d1=dict({1: "Orange", 2: "Mango", 3: "Banana"})
>>> d2=dict([(1, "Red"),(2, "Green"),(3, "Yellow")])
>>> d3=dict(one=1, two=2, three=3)
>>> d2
{1: 'Red',2: 'Green',3: 'Yellow'}
>>> d3
{'one':1, 'two':2, 'three':3}
Output:
Enter the number of elements:3
Enter elements:
Enter key: 1
Enter value: Orange
Enter key: 2
Enter value: Mango
Enter key: 3
Enter value: Banana
{'1': 'Orange', '2': 'Mango', '3': 'Banana'}
Output:
Enter the number of elements: 3
Enter elements: Name Nilesh
Enter elements: Roll_no 54
Enter elements: Phone 9898989898
The created dictionary is: {'Name': 'Nilesh', 'Roll_no': '54', 'Phon
e': '9898989898'}
The preceding program takes elements in the form of a string from the user. It breaks the
inputted string into key-value pairs by a space separator. It inserts those broken strings as
elements in the dictionary.
Output:
Enter the number of elements:2
Enter Key: Name
Enter Value: Vijay
Enter Key: Age
Enter Value: 30
The created dictionary is: {'Name': 'Vijay', 'Age': '30'}
1. Using the key inside square brackets like we used to use the index inside square
brackets.
>>> d1={'Name': 'Nilesh', 'Roll_no': '54', 'Phone': '9898989898'}
>>> d1['Name']
'Nilesh'
2. Using the get() method and passing the key as a parameter inside this method.
>>> d1.get('Roll_no')
54
>>> d1.get('Name')
'Nilesh'
Output:
64
{1: 1, 2: 8, 3: 21, 5: 125}
Output:
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}
Output:
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}
Output:
{}
Output:
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘cubes’ is not defined
Output:
1
8
21
64
125
Output:
iphone
Samsung
67000
87000
Examples:
Add Elements to the nested dictionary:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS', "price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
#Adding a new dictionary in the mobiles dictionary
mobiles[3] = {}
mobiles[3]['Company'] = 'Nokia'
mobiles[3]['model'] = 'A7'
mobiles[3]['OS'] = 'Android'
mobiles[3]['price'] = 17000
print(mobiles[1])
print(mobiles[2])
print(mobiles[3])
Output:
{'Company': 'iphone', 'model': 'XR', 'OS': 'IOS', 'price': 67000}
{'Company': 'Samsung', 'model': 'Note 10', 'OS': 'Android', 'price':
87000}
{'Company': 'Nokia', 'model': 'A7', 'OS': 'Android', 'price': 17000}
There is another simple approach to add a dictionary inside a dictionary let’s understand it
with an example:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS', "price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
#Adding new dictionary in the mobiles dictionary
mobiles[3] = {'Company':'Nokia', 'model':'A7', 'OS':'Android',
'price':17000}
print(mobiles[1])
print(mobiles[2])
print(mobiles[3])
Output:
{'Company': 'iphone', 'model': 'XR', 'OS': 'IOS'}
{'Company': 'Samsung', 'model': 'Note 10', 'OS': 'Android'}
{'Company': 'Nokia', 'model': 'A7', 'OS': 'Android'}
Example:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS',
"price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000}
}
mobiles[3] = {'Company':'Nokia', 'model':'A7', 'OS':'Android',
'price':17000}
del mobiles[3]
print(mobiles)
Output:
{1: {'Company': 'iphone', 'model': 'XR', 'OS': 'IOS', 'price': 67000
}, 2: {'Company': 'Samsung', 'model': 'Note 10', 'OS': 'Android', 'p
rice': 87000}}
Example:
mobiles = {
1: {'Company':'iphone', 'model':'XR', 'OS':'IOS',
"price":67000} ,
2: {'Company':'Samsung', 'model':'Note 10', "OS":'Android',
'price':87000},
3: {'Company':'Nokia', 'model':'A7', 'OS':'Android',
'price':17000}
}
for i , nes_dict in mobiles.items():
print(i, 'Product information')
for j in nes_dict:
print(j, nes_dict[j])
print("************")
Output:
1 Product information
Company iphone
model XR
OS IOS
price 67000
************
2 Product information
Company Samsung
model Note 10
OS Android
price 87000
************
3 Product information
Company Nokia
model A7
OS Android
price 17000
************
Sr. Built-in
Description Example
No. Method
The keys() method returns a >>> dict1={1:1,2:2,3:3}
1 keys() list of keys in a Python >>> dict1.keys()
dictionary. dict_keys([1, 2, 3])
Likewise, the values() method >>> dict1.values()
2 values() returns a list of values in the dict_values([1, 2, 3])
dictionary.
The copy() method creates a >>> newdict=dict1.copy()
shallow copy of the Python >>> newdict
dictionary. {1:1,2:2,3:3}
3 copy() A shallow copy only copies
contents, and the new construct
points to the same memory
location.
>>> dict1.items()
This method returns a list of
4 items() dict_items([(1, 1), (2, 2), (3,
key-value pairs.
3)])
>>> newdict={3:3,1:1,4:4,9:9}
Removes the last inserted key-
5 popitem() >>>newdict.popitem()
value pair.
(9,9)
This method creates a new >>>
Python dictionary from an newdict.fromkeys((1,2,3,4,7),0)
existing one. To take an {1: 0, 2: 0, 3: 0, 4: 0, 7: 0}
example, we try to create a
new dictionary from newdict.
6 fromkeys() While the first argument takes
a set of keys from the
dictionary, the second takes a
value to assign to all those
keys. But the second argument
is optional.
It is used to set the key to the >>> dict1={1:4,2:6,3:9}
default value if the key is not >>> p=dict1.setdefault(2)
7 setdefault() specified in the dictionary. If >>> print(p)
the key does not exist; inserts 6
the key with specified value.
3.5 Strings
A string object is one of the sequence data types in Python. It is an immutable sequence of
Unicode characters. Strings are objects of Python's built-in class 'str'. String literals are
written by enclosing a sequence of characters in single quotes ('hello'), double quotes
("hello") or triple quotes ('''hello''' or """hello""").
>>> str1='hello'
>>> str1
'hello'
>>> str2="hello"
>>> str2
'hello'
>>> str3='''hello'''
>>> str3
'hello'
>>> str4="""hello"""
>>> str4
'hello'
Note that the value of all the strings, as displayed by the Python interpreter, is the same
('hello'), irrespective of whether single, double or triple quotes were used for string formation.
If it is required to embed double quotes as part of a string, the string itself should be put in
single quotes. On the other hand, if a single-quoted text is to be embedded, the string should
be written in double quotes.
>>> str1='Welcome to "Sanjivani KBP Polytechnic" of Sanjivani Group'
>>> str1
'Welcome to "Sanjivani KBP Polytechnic" of Sanjivani Group'
>>> str2="Welcome to 'Sanjivani KBP Polytechnic' of Sanjivani Group"
>>> str2
"Welcome to 'Sanjivani KBP Polytechnic' of Sanjivani Group"
The string is an immutable object. Hence, it is not possible to modify it. The attempt to
assign different characters at a certain index results in errors.
>>> myString[1]='a'
TypeError: 'str' object does not support item assignment
You can specify the width of integer and float objects. Here, integers a, b and c will occupy
the width of 3 characters in the formatted string. Additional spaces will be padded to the left.
>>> a=1
>>> b=11
>>> c=111
>>> "a=%3d b=%3d c=%3d" % (a, b, c)
'a= 1 b= 11 c=111'
In the above example, %5.2 specifies the width of float, where 5 is for total characters and 2
is for decimals. So, the result would be '55.50'.
The width of a string can also be specified. The default alignment is right. For left alignment,
give a negative sign to width.
>>>'%4s' % 'abc'
>>>' abc'
>>>'%6s' % 'abc'
>>>' abc'
>>>'%-6s' % 'abc'
>>>'abc '
>>>a='abc'
>>>'%-6s' % a
>>>'abc '
format() method
The format() method can handle complex string formatting more efficiently. This method
of in-built string class provides the ability to do complex variable substitutions and value
formatting. This new formatting technique is regarded as more elegant. The general syntax of
the format() method is as follows:
string.format(str1, str2,...)
The string itself contains placeholders {}, in which the values of variables are successively
inserted.
>>>name="Bill"
>>>age=25
>>>"My name is {} and I am {} years old.".format(name, age)
'My name is Bill and I am 25 years old.'
>>>myStr = "My name is {} and I am {} years old."
>>>myStr.format(name, age)
'my name is Bill and I am 25 years old.'
You can also specify formatting symbols by using : instead of %. For example, instead
of %s use {:s} and instead of %d use {:d}.
>>> "My name is {:s} and I am {:d} years old.".format(name, age)
'My name is Bill and I am 25 years old.'
String alignment is done with <, > and ^ symbols in the place holder causing left, right and
center alignment, respectively. Default is left alignment.
>>> '{:>10}'.format('test')
' test'
>>> '{:<10}'.format('test')
'test '
>>> '{:^10}'.format('test')
' test '
upper():
Replaces the lowercase characters in a string with corresponding uppercase characters.
>>> mystr='Python'
>>> mystr.upper()
'PYTHON'
lower():
Replaces the uppercase characters in a string with corresponding lowercase characters.
>>> mystr='PYTHON'
>>> mystr.lower()
'python'
title():
Returns the string with the first character of each word converted to uppercase.
>>> mystr='welcome to sanjivani kbp polytechnic'
>>> mystr.title()
'Welcome To Sanjivani Kbp Polytechnic'
find():
The find() method finds the first occurrence of a substring in another string. If not found, the
method returns -1.
>>> mystr='welcome to sanjivani kbp polytechnic'
>>> mystr.find('kbp')
21
>>> mystr.find('xyz')
-1
count():
The count() method returns the number of occurrences of a substring in the given string.
>>> mystr='welcome to sanjivani kbp polytechnic'
>>> mystr.count('kbp')
1
isalpha():
The isalpha() method returns true if all the characters in a string are alphabetic letters (a-z or
A-Z), otherwise it returns false.
>>> mystr='SanjivaniKBP'
>>> mystr.isalpha()
True
>>> mystr='Sanjivani KBP'
>>> mystr.isalpha()
False
isdigit():
The isdigit() is method returns true if all the characters in string are digits (0-9), if not, it
returns false.
>>> str1='2000'
>>> str1.isdigit()
True
>>> str2='2,000'
>>> str2.isdigit()
False
islower():
The islower() method returns true if all the characters in the string are lowercase characters,
else it returns false.
>>> str1='python'
>>> str1.islower()
True
>>> str2='Python'
>>> str2.islower()
False
isupper():
The isupper() method returns true if all the characters in the string are uppercase characters,
else it returns false.
>>> var='SANJIVANIKBP'
>>> var.isupper()
True
>>> var='SANJIVANIkbp'
>>> var.isupper()
False
3.6 Programs
P1: Python Program to Add Two Matrices
X = [[1,2,3],
[4,5,6],
[7,8,9]]
Y = [[10,11,12],
[13,14,15],
[16,17,18]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
X = [[1,2,3],
[4,5,6],
[7,8,9]]
Y = [[10,11,12],
[13,14,15],
[16,17,18]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows of X
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
X = [[1,2],
[4,5],
[7,8]]
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
P4: Python program to copy all elements of one array into another array
arr1 = [1, 2, 3, 4, 5]
arr = [1, 2, 3, 4, 5]
print("Original array: ")
for i in range(0, len(arr)):
print((arr[i]), end=" ")
print("Array in reverse order: ")
#Loop through the array in reverse order
for i in range(len(arr)-1, -1, -1):
print((arr[i]), end=" ")
arr = [1, 2, 3, 4, 2, 7, 8, 8, 3]
print("Duplicate elements in given array: ")
#Searches for duplicate element
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] == arr[j]):
print(arr[j])