Python 2
Python 2
40
on (BBA (CA)- Sem. V]
e 3
u 2
h 2
r 2
t 2
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
Python [BBA (CA) Sem. V) 1.41 Introduction to Python
Example:
list1 = "apple", "banana", "cherry")
print(listl)
Output:
["apple", "banana" "cherry")
[1, 2]
['a', 'b']
[1, 2, 3, 4)
('a', 'b'
Python [BBA (CA)- Sem. V] 1.42 Introductlon to Pyth.
1.7.2 List Operation
Lists respond to the +and * operators much like strings; they mean concatenation an
Tepetition here too, except that the result is a new list, not a string.
In fact, lists
respond to all of the general sequence operations we used on strings
the previous section.
Python Expression Results Description
len([4, 5, 6, 7]) Length
(1,2,3] +[4,5,6] [1,2,3,4, 5,6] Concatenation
('Hi!)"3 ['Hi!, Hi!,'Hi!] Repetition
3 in [1, 2, 3] True Membership
for i in (1, 2,3): print i, 123 Iteration
1.8
TUPLE-INTRODUCTION, ACCESSING TUPLES, OPERATIONS
WORKING,FUNCTION AND METHODS, EXAMPLES
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets. This Python Data Structure is like a list in Python, is
heterogeneous container for objects.
The differences between tuples and lists are, we cannot change the elements of
tunle once it is assigned whereas 1n a list, elements can be changed. This means tha
Twhile vOu can reassign or delete an enture tuple, you cannot do the same to a sing
item or a slice. Tuples use parentneses,Whereas lists use square brackets
ython (BBA (CA) - Sem.V] 1.45
Introduction to Python
Advantages of Tuple:
1. Processing of Tuples are faster than Lists.
2. It makes the data safe because tuples are immutable
and hence cannot be
changed.
3. Generally tuples are used for heterogeneous (different) datatypes
and list for
homogeneous (similar) datatypes.
4. Tuples are used for String formatting.
Difference between Tuples and Lists:
1. The syntax of tuples is shown by parenthesis) whereas the syntax of lists
is shown
by square brackets[ ).
2. List has variable length, tuple has fixed length.
3. List has mustable nature, tuple has immutable nature.
4. List has more functionality than the tuple.
5. Typles are heterogeneous while lists are homogeneous. One has to
deal
individually with the items.
6. Tuples show structure whereas lists show order.
reating Tuple:
Atuple is created by placing all the items (elements) inside a
by comma. The parentheses are optional but is a good practice parentheses ), separated
to
have any number of items and they may be of different types write it. A tuple can
string etc.). (integer, float, list,
For example:
tup1 = ("apple", "orange", 2018) ; tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing.
tup1 = (0;
To write a tuple containing a single value you
have to include a comma, even
though there is only onevalue:*
tup1 = (50,);
Like string indices, tuple indices start at 0, and they
SO on.
can be sliced, concatenated, and
(1, 2, 3)
(1, 'Hello', 3.4)
('Hello', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'tybca' )
3
4.6
tybca
Methods:
Python Tuple Methods:
JA method is asequence ofinstructions toperform on something. Unlike afunction, it
does modify the construct on which it is called. You call a method using the dot
operator in python. Python has two built-in methods that you can use on tuples.
1. index(x): Return index of first item that is equal to x.
Example:
>>> a=(1, 2,3,2,4,5,2)
>>> a.index(2)
Output: 1
As you can see,we have 2s at indices 1,3, and 6. But it returns only thefirst index.
2. Count(x): Return the number of items is equal to x.
Example:
>>> a=(1,2,3,2,4,5,2)
>>> a.cOunt (2)
Output: 3
Program 1.32: Write a Python program to create a list of tuples with the first element as
the number and second element as the square of the number.
1_range=int (input ("Enter the lower range:"))
u_range=int(input(" Enter the upper range:"))
a=[(x,x**2) for x in range(1_range, u_range+1)]
print (a )
Output:
Enter the lower range:1
Enter the upper range:4
((1, 1), (2, 4), (3, 9), (4, 16)]
Examples:
Program 1.33: Write a Python program to add an item in a tuple.
#create a tuple
tuplex =(4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it
will create a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
Python (BRA (CA) Sem. V) 1.52
totroductlon to Py
Tuplex - tuplex[ :S] + (15, 20, 25) + tuplex[ :5]
print(t uplex)
#converting the tuple to list
listx list(tuplex)
SUse different ways to add items in list
listx.append(30)
tuplex tuple(listx)
print(tuplex)
Output:
(4, 6, 2, 8, 3, 1)
(4, 6, 2, S, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4,
6, 2, 8, 3)
(4, 6, 2, 8, 3, 15, 20, 25, 4,
6, 2, 8, 3, 30)
Program 1.34: Write a Python program to convert
a tuple to a string.
tup = ('e', 'x', 'e
'r','c', 'i', 's', 'e', 's')
str ="join(tup)
print(str)
Output:
exercises
Program 1.35: Write a Python program to get the 4"
from last of a tuple. element from front and 4" elemen!
#Get an item of the tuple
tuplex = ("p", "y", "t", "h", "o", "n", "b", "o"", "o", "k")
print (tuplex)
#Get item (4 element )of the tuple
by index
item = tuplex[3)
print(item)
#Get item (4" element from last)by
index negative
item1 = tuplex[ -4]
print(item1 )
Output:
(Cp', 'y', 't', h', 'o' 'n', "b', 'o', 'o', 'k'
h
Python [BBA (CA) - Sem. V) 1,53 Introduction to Python
Program 1.36: Write a Python program tofind the repeated items of a tuple.
#Create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print (tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count (4)
print (count)
Output:
(2, 4, 5, 6, 2, 3, 4, 4, 7)
Program 1.37: Write a Python program to check whether an element exists within a tuple.
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print ("r" in tuplex)
print (5 in tuplex)
Output:
True
False
NmYYYNYNYYYTrYYYY YYYYTA
DICTIONARIES-INTRODUCTION, ACCESSING VALUES IN
1.9 DICTIONARIES, WORKING WITH DICTIONARIES, PROPERTIES,
FUNCTION, EXAMPLES
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Dictionaries are optimized to retrieve values when the key is known.
Dictionaries are Python's implementation of a data structure that is more generally
known as an associative array. Adictionary consists of a collection of key-value
Each key-value pair maps the key to its associated value. pairs.
Creation of Dictionary:
Creating a dictionary is as simple as placing items inside curly braces (}
comma. An item has a key and the corresponding value separated by
value. expressed as a pair, key:
Each key is separated from its value by a colon (:), the
items are separated by commas,
and the whole thing is enclosed in curly braces. An
items is written with just twO curly braces, like this: {}. empty dictionary without any
Keys are unique within a dictionary while values may not
be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such as
strings, numbers, or tuples.
Python [BBA (CA) - Sem. V]
1.54
Introductlon to Pythe
Syntax:
dictionary_name ={
<key>: <value>,
<key>: <value>,
<key>: <value>
}
Or
dictionary_name =dict([
(<key>, <value>),
(<key>, <value),
(<key>, <value>)
J)
Where dict is built-in
function.
Example:
# empty dictionary with name dict
dict = {}
dicti['age'] =25
#Output: {'age': 25, 'name': '0mkar"}
print (dict1)
# add item
dict1['address' ] 'pune'
# Output: {'address':'pune, 'age': 25, 'name': Omkar'}
print(dict1)
Program 1.39: Print all key names in the dictionary, one by
one.
dict1 {'name':'Omkar', 'address': 'pune',
for x in dict1: print (x)
'phone':9897965867}
Output:
phone
name
address
name Omkar
ython [BBA (CA) - Sem. V] 1.57 Introduction to Python
Example:
>>» d= {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d
More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins,
means the second occurrence will override the first.
Example:
dict = {'Name' : 'Omkar', 'Age ': 20, ' Name': 'Mani'}
print "dict[ 'Name ']: ", dict[ "Name']
Output:
dict['Name']: Mani
Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key] is not allowed. <
Example:
dict = (['Name'): 'Omkar', 'Age': 20}
print "dict[ 'Name']: ", dict[ 'Name']
# Output: error
»» d[(2, 1)]
'c'
1.9,4 Function and Methods
Python includes the following dictionary functions:
1. cmp(dicti, dict2): Compares elements of both dict.
2. len(dict): Gives the total length of the dictionary. This would
number of items in the dictionary. be equal to the
3. str(dict): Produces a printable string representation of a
4. type(variable): Returns the type of the passed
dictionary.
dictionary, then it would return a dictionary type. variable. If passed variable is
Example:
dict = {'Name' : 'abc', 'Age': 20);
#usage of len( ) method
print "Length: %d" %len (dict) #0utput:
Length: 2
# usage of type() method
Python [BBA (CA) - Sem. V] 1.60
Introduction to
print "variable Type: %s" %type(dict)
FOutput:Variable Type: <type 'dict'>
#usage of str() method.
print "Equivalent String: %s" %str (dict)
F0utput: Equivalent String: {'Age': 20, 'Name': abc'}
Python includes following dictionary
methods:
. dict.clear): Removes all elements of dictionary dict.
2. dict.copy): Returns a shallow copy of
3. dictionary dict.
dict.fromkeys(): Create a new dictionary with keys from seq and
value. values se
4. dict.get (key, default=None): For key key, returns value
dictionary. or default if kev
5. dict.has_key (key): Returns true if
6. dict.items(0: Returns a list of key in dictionary dict, false otherwise.
7. dict.keys(): Returns list dict's (key, value) tuple pairs.
of dictionary dict's keys.
8. dict.setdefault(key,
if key is not already indefault=None): Similar to get), but will set dict{key]=dei:
9. dict.update(dict2): Adds dict.
10. dict.values (): dictionary dict2's key-values
Returns list of dictionary dict's pairs to dict.
Program 1.43: To show usage of all values.
dict = {'Name': methods of dictionary.
# usage of items 'abc', 'Age': 20}
() method.
print("Value: %s" % dict.items())
# usage of
update() method.
dict = {'Name' :
dict1 = {'Sex': 'abc', 'Age': 20}
'female' }
dict.update(dict1)
print("Value: %s" % dict)
# usage of
keys() method.
print("Value: %s" % dict.keys()
# usage of
values() method.
print("Value: %s" % dict.values
())
# usage of
copy() method.
dict2 = dict.copy()
print("New Dictionary : %s" %
# clear() method. str(dict2))
print("Start Len: 3d" %len(dict))
dict.clear()
print("End Len: %" %
len(dict))
Python [BBA (CA) - Sem. V) 1.61 Introduction to Python
Output:
Value: dict_items([('Name 'abc'), ('Age', 20)])
Value: {'Name': ' abc', 'Age': 20, Sex': 'female'}
value: dict _keys(['Name 'Age', 'Sex'])
value: dict_values(['abc' 20, 'female'])
New Dictionary: {'Name': 'abc', 'Age': 20, 'Sex': 'female '}
Start Len: 3
End Len: 0
Examples:
Program 1.44: Write a Python script to sort (ascending and descending) a dictionary by
value.
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: e}
print('Original dictionary :',d)
sorted _d =dict (sorted(d. items (), key=operator. itemgetter (1)))
print('Dictionary in ascending order by value : ',sorted_d)
sorted _d = dict(sorted(d. items(), key=operator. itemgetter(1), reverse=True) )
print('Dictionary in descending order by value:',sorted_d)
Output:
Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, @: e}
Dictionary in ascending order by value: {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Dictionary in descending order by value: (3: 4, 4: 3, 1: 2, 2: 1, 0: 0}
Program 1.45: Write a Python script to add a key to adictionary.
Sample Dictionary: {0: 10, 1: 20) Expected Result :{0: 10, 1: 20, 2: 30}.
d= (0:10, 1:20)
print (d)
d. update({2:30})
print (d)
Write aPython script to concatenate following dictionaries to create a new
one.
Sample Dictionary:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = }
for d in (dic1, dic2, dic3): dic4 . update (d)
print (dic4)
Python [BBA (CA) Sem. V] 1,62 1ntroduction to hn
Program 1.46: Write a Python script to check if agiven key already exists in: adictionan
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60)
def is_key_present (x) :
if x in d:
print('Key is present in the dictionary')
else:
print("Key is not present in the dictionary')
is_key_present (5)
is_key_present (9)
Output:
Key is present in the dictionary
Key is not present in the dictionary
Program 1.47: Write a Python program to iterate over dictionaries using for loops.
d= {'x': 10, 'y': 20, 'z': 30}
for dict_key, dict value in d.items():
print (dict_key, '->',dict_value)
Output:
y -> 20
Z -> 30
X -> 10
Program 1.48: Write a Python script to generate and print a dictionary that contains
number (between 1and n) in the form (x, x*x). Sample Dictionary (n =5) : Expected Out
:{1: 1, 2: 4, 3:9, 4: 16, 5: 25)
n=int(input("Input a number "))
d = dict()
Program 1.50: Write a Python program to combine two dictionary adding values for
common keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {"a': 300, 'b': 200, 'd':400}
Sample output: Counter ({'a': 400, 'b': 400, 'd': 400, 'c': 300})
from collections import Counter
d1 = {"a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = Counter(d1) + Counter (d2)
print (d)
rogram 1.51: Write a Python program to create and display all combinations of
etters, selecting each letter from a different key in a dictionary. Sample data :
1a',b], 2:[C,d]} Expected Output:
ac
ad
bc
bd
import itertools
d ={'1':['a','b'], '2':['c','d']}
for combo in itertools. product(*[d[k] for k in sorted (d. keys() )]):
print("".join(combo) )
TOgram 1.52: Write a Python program to create a dictionary from two lists without
osing duplicate values.
Sample lists: ['Class-v', 'Class-VI', 'Class-VII', Class-VIIT'l, [1, 2, 2, 3]
Expected Output: defaultdict(<class 'set'>, {'Class-VII': (2), 'Class-VI':
{2}, 'C1ass -VIII': (3}, 'Class-V': {1}})
from collections import defaultdict
class_list = ['C1lass -V', 'Class-VI', 'Class -VII', 'Class-VIII']
id_list = [1, 2, 2, 3]
temp = defaultdict(set)
for c, i in zip(class_list, id_list):
temp[c].add(i)
print (temp)
hon [BBA (CA) Sem. V] 1,64
Introduction to
Program 1.53: Write a Python program to match key values in two dictionaries
dictionary: ('key1': 1, 'key2': 3, 'key3': 2), ('key1': 1, 'key2': 2} Expected output: Sat,
present in both x and y. keyl:;
X= {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items ()) & set (y.items()):
Print( %s: %s is present in both x and y' % (key, value))
By default, parameters have apositional behavior and you need to inform them in the
same order that they were defined. Every function must be defined before it iscalled.
How function works in Python:
def functionName():
functionName():
Fig. 1.23
Example:
# function without parameters
def my_function ():
print("Hello from a function")
# A string as input parameter and prints it on standard screen.
def fun( str ):
"This prints a passed string into this function"
print str
return
my_function()
Output: 'Hello from a function