You are on page 1of 61

List, Tuples, Dictionaries,Sets

List methods:
Method Example Description
sum() sum(lst) Returns sum of all elements in the
list
index() list.index(x) Returns first occurrence of x in the
list
append() list.append(x) Appends x at the end of the list
insert() list.insert(i,x) Inserts x into the list in the position
specified by I
copy() list.copy() Copies all the list elements into a
new list and returns it
extend() list.extend(list1) Appends list1 to list
count() list.count(x) Returns number of occurrence of x
in the list
remove() list.remove(x) Removes x from the list
pop() list.pop() Removes the ending element from
the list
sort() list.sort() Sorts the elements of the list into
ascending order
Method Example Description
Reverse() list.reverse() Reverse the sequence of elements
into the list
Clear() list.clear() Deletes all elements from the list
Example program on List methods
num=[1,2,3,4,5]
print(sum(num))
print('Index of 2 is',(num.index(2)+1))
num.append(6)
print('After appending 6',num)
num.insert(0,7)
print('After appending 7 at 0 th position',num)
num[0]=8
print(num)
num1=num.copy()
print('Newly Created List',num1)
num.extend(num1)
print('Num after appending num1',num)
print('No. of times 5 found in the list',num.count(5))
num.remove(5)
print('list after removing 5',num)
num.pop()
print('After removing ending element',num)
num.sort()
print('List after sorting',num)
num.reverse()
print('List after reversing',num)
num.clear()
print('List after removing all elements',num)
num=[10,20,30,40,50]
print('Biggest element in list',max(num))
print('Smallest element in list',min(num))
Nested List:
A list within another list is called as Nested List. When we take a list as an
element in another list, then the list is called a Nested List.
For Example:
We have two list a and b as:
a=[80,90]
b=[10,20,30,a]
print(b) #[10,20,30,[80,90]]
The element of b appears:
[10,20,30,[80,90]]
The last element [80,90] represents a nested list. So ‘b’ has 4 elements
and they are:
b[0]=10
b[1]=20
b[2]=30
b[3]=[80,90]
List Comprehensions:
List comprehensions represent creation of new lists from an iterable
object(like a list, set, tuple, dictionary or range) that satisfy a given
condition.
List comprehension contain very compact code usually a single
statement that performs a task.
Example 1:
We want to create a list with sequence of integers from 1 to 10. We
can write code as:
squares=[]
for x in range(1,11):
squares.append(x**2)
Output: [1,4,9,16,25,36,49,64,81,100]
The preceding code will create ‘squares’ list with the elements as
shown below:
squares=[x**2 for x in range(1,11)]

This is called List Comprehension. From this, we can understand that a


list comprehension consists of square braces containing an
expression(i.e x**2). After the expression, a for loop and then zero or
more if statements can be written.
Syntax:
[expression for item1 in iterable if statement1
for item2 in iterable if statement2
for item3 in iterable if statement3……..]

Here ‘iterable’ represents a list, set, tuple, dictionary or range object.


The result of a list comprehension is a new list that contains elements
as a result of executing the expression according to the for loops and if
statements.
Example 2:
Suppose we want to get squares of integers from 1 to 10 and take
only the even numbers from the result, we can write list
comprehension as:
even_squares=[x**2 for x in range(1,11) if x%2==0]
Output: [4,16,36,64,100]
The same list comprehension can be written without using the if
statement as:
even_squares=[x**2 for x in range(2,11,2)]
Example 3: If we have two lists ‘x’ and ‘y’ and we want to add each
element of ‘x’ with each element of ‘y’, we can write for loop as:
x=[10,20,30]
y=[1,2,3,4]
lst=[ ]
for i in x:
for j in y:
lst.append(i+j)
Output:[11,12,13,14,21,22,23,24,31,32,33,34]
The same result can be achieved using list comprehension as:
lst=[i+j for i in x for j in y]
Or
We can directly mention the lists in the list comprehension as:
lst=[i+j for i in [10,20,30] for j in [1,2,3,4]]

The previous list comprehension can be written using strings as:


lst= [i+j for i in ‘ABC’ for j in ‘DE’]
In this case the output will be:
[‘AD’, ‘AE’, ‘BD’, ‘BE’, ‘CD’, ‘CE’]
EXAMPLE:
num1=[1,2,3,4,5]
num2=[10,11,1,2]
We want to create another list ‘num3’ with numbers present in ‘num1’ but not in ‘num2’.
The logic looks like:
num3=[]
for i in num1:
for j in num2:
if i not in num2:
num3.append(i)
print(num3)
Output:[3,4,5]
The same can be achieved using list comprehension as:
num3=[i for i in num1 if i not in num2]
Tuples
Tuples:
Tuples are similar to lists but the main difference is tuples are
immutable where as lists are mutable.
Since tuples are immutable, once we create a tuple we cannot modify
its element.
Hence we cannot perform operations like append(), extend(), insert(),
remove(), pop() and clear() on tuples.
Tuples are generally used to store data which should not be modified
and retrieve that data on demand.
Creating Tuples:
We can create a tuple by writing elements separated by commas inside
parantheses()
Example:
tup1= ( ) # empty tuple
Example: tuple with one element
tup2= (10,)
Example: tuple with different types of elements
tup3= (10,20,-30.1,40.5, ‘Kadapa’, ‘Tirupati’)
Example: tuple with only one type of elements
tup4= (10,20,30) # tuple with integers
Note:
If we do not mention any brackets and write the elements separating them by
commas, then they are taken by default as a tuple.
tup5= 1,2,3,4,’kvk’ # no braces
Accessing the tuple elements:
Accessing the elements from a tuple can be done by using indexing or slicing.
This is same as that of a list.
Example:
tup= (50,60,70,80,90,100)
print(tup[0]) #50
print(tup[5]) #100
print(tup[-1]) #100
print(tup[-6]) #50
print(tup[:]) #(50,60,70,80,90,100)
print(tup[1:4]) #(60,70,80)
print(tup[::2]) #(50,70,90)
print(tup[::-2]) #(100,80,60)
print(tup[-4:-1]) # here step size is -1, so output(70,80,90)
Example:
student=(10,’kvk’,50,60,55,61,70)
rno,name=student[0:2]
print(rno) #10
print(name) # kvk
Basic Operations on Tuples:
The 5 basic operations:
Finding Length
Concatenation
Repetition
Membership
Iteration Operation
Consider the following example:
student=(10,’kvk’,50,60,70,80,90)
print(len(student)) # 7
We can concatenate or join two tuples and store the result in new tuple.
For example, the student paid a fees of Rs. 25,000.00 every year for 4
terms, then we can create a ‘fees’ tuple as:
fees= (25000.00)*4 # repeat the tuple elements for 4 times
print(fees) #(25000.00,25000.00, 25000.00, 25000.00)
We can concatenate the ‘student’ and ‘fees’ tuples together to form a
new tuple ‘student1’ as:
student1= student+fees
print(student1)
#(10,’kvk’,50,60,70,80,90,25000.00,25000.00,25000.00,25000.00)
Dictionaries:
A Dictionary represents a group of elements arranged in the form of
key-value pairs. In the dictionary first element is considered as ‘key’
and the immediate next element is taken as its ‘value’.
The key and value are separated by a colon ( : )
All the key value pairs are inserted in curly braces {}
Example: dict = { ‘Name’:’KVK’, ‘Id’:200, ‘Salary’:9999.99}
Write a Python program to create a dictionary with employee details
and retrieve the values upon giving the keys
dict={‘Name’:’kvk’, ‘Id’:200, ‘salary’:9999.50}
print(‘Name of the employee :’, dict[‘Name’]);
print(‘Salary=‘, dict[‘salary’])
Print(‘Id Number=“,dict[‘Id’])
Output:
Name of the Employee :kvk
Salary=9999.50
Id Number=200
Operations on Dictionaries:
To access the elements of a dictionary we should not use indexing or
slicing. For example dict[0] or dict[1] etc expressions will give error.
To access the value associated with a key, we can mention name inside
the square braces, as: dict[‘Name’]. This will return the value associated
with ‘Name’.
To find number of key-value pairs in Dictionary:
We can use the len() function to find number of key-value pairs in a
dictionary
dict={‘Name’: kvk, ‘Id’: 200, ‘Salary’:99.50}
n=len(dict)
print(‘No. of key-value pairs =‘, n)
We can modify the existing value of a key by assigning new value, as
dict[‘Salary’]=109.50
Here the ‘Salary’ value is modified as ‘109.50’. The previous value of
‘Salary’ i.e 99.50 is replaced by new value i.e 109.50
We can also insert a new key-value pair into existing Dictionary. This is
done by mentioning the key and assigning a value to it as shown in the
following:
dict[‘Dept’]=‘Technical’
Here, we are giving a new key ‘Dept’ and its value ‘Technical’. This pair is
stored into the dictionary ‘dict’. Now if we display the dictionary using
print(dict), it will display:
{‘Name’: ‘kvk’, ‘Dept’:’Technical’, ‘Id’:200,’Salary’:109.50}
To test whether a ‘key’ is available in a dictionary or not, we can use ‘in’
and ‘not in’ operators. These operators return either ‘True’ or ‘False’.
Example:
‘Dept’ in dict # check if ‘Dept’ is a key in dict
The preceding statement will give:
True
Example:
‘Gender’ in dict #check if ‘Gender’ is a key in dict
The preceding statement will give:
False
We can use any datatypes for values. For example, a value can be number,
string,list, tuple or another dictionary. But the keys should obey the
following rules:
1. Keys should be unique. It means duplicate keys are not allowed. If we
enter same key again, the old key will be overwritten and only the
new key will be available. Consider the following example:
emp={‘kvk’:10, ‘nani’:20, ‘kvk’:30}
print(emp)
output: {‘kvk’:30, ‘nani’:20}
2. Keys should be immutable type. For example, we can use a number,
string or tuples as keys since they are immutable. We cannot use list or
dictionaries as keys. If they are used as keys, we will get ‘TypeError’.
Example:
emp={[‘kvk’]:10, ‘nani’:20, ‘sunny’:30} #[‘kvk’] is a list element- so error
Dictionary Methods:
Various methods are provided to process the elements of a dictionary.
1. clear(): Ex:d.clear()-→ Removes all key-value pairs from dictionary ‘d’
2. copy(): Ex:d1=d.copy() – Copies all elements from ‘d’ into a new
dictionary ‘d1’
3. fromkeys(): Ex:d.fromkeys(s,[,v]): creates a new dictionary with keys
from sequence ‘s’ and values all set to ‘v’
4. get(): Ex: d.get(k,[,v]): Returns the value associated with key ‘k’. If key
is not found, it returns ‘v’
5. items(): Ex: d.items()
Returns an object that contains key-value pairs of ‘d’. The pairs are stored
as tuples in the object.
6. keys(): Ex: d.keys()
Returns a sequence of keys from the dictionary ‘d’
7. values(): Ex: d.values()
Returns a sequence of values from the dictionary ‘d’
8. update(): Ex: d.update(x)
Add all elements from dictionary ‘x’ to ‘d’
9. pop(): Ex: d.pop(k,[,v])
Removes the key ‘k’ and its value from ‘d’ and returns the value. If key is
not found, then the value ‘v’ is returned. If key is not found and ‘v’ is not
mentioned then ‘KeyError’ is raised.
10. Setdefault(): d.setdefault(k,[,v])
If key ‘k’ is found, its value is returned. If key is not found, then the k,v
pair is stored into the dictionary ‘d’.
Write a Python program to retrieve keys, values and key-value pairs from
a dictionary
dict={‘Name’: kvk, ‘Id’: 100, ‘Salary’:99.50}
print(dict)
#display only keys
print(‘Keys in dict =‘, dict.keys())
#display only values
print(‘values in dict=‘, dict.values())
#display both key and value pairs as tuples
print(‘items in dict= ‘, dict.items())
Output:
{‘Name’:’kvk’, ‘Id’:100, ‘Salary’:99.50}
Keys in dict = dict_keys([‘Name’, ‘Id’, ‘Salary’])
Values in dict= dict_values([‘kvk’,100,99.50])
Items in dict= dict_items([(‘Name’,’kvk’),(‘Id’,200),(‘Salary’,99.50)])
A Python program to create a dictionary from keyboard and display
elements
x={ }
print(‘ How many elements? ‘, end= ‘ ‘)
n=int(input())
for i in range(n):
print(‘enter key: ‘, end=‘ ‘)
k=input()
print(‘Enter its value: ‘, end=‘ ‘)
v=int(input())
x.update({k:v})
print(‘ The dictionary is ‘, x)
Using for loop for dictionaries
For loop is very convenient to retrieve the elements of a dictionary.
Example:
colors= { ‘r’: “Red”, ‘g’: “green”, ‘b’:”Blue”, ‘w’:”white”}
Here ‘r’, ‘g’, ‘b’, ‘w’ are keys and “Red”, “green”, “Blue”, “white” indicate
values.
Suppose we want to retrieve only keys from ‘colors’ dictionary, we can
use a for loop as:
for k in colors:
print(k)
Suppose we want to retrieve values, then we can obtain them by passing
the keys to colors dictionary, as: colors[k].
The following for loop retrieves all the values from the colors dictionary:
for k in colors:
print(colors[k])
Since values are associated with keys, we can retrieve them only when
we mention the keys.
Suppose we want to retrieve both the keys and values, we can use the
items() method in for loop as:
for k, v in colors.items():
print(‘key = { } value={ }’.format(k,v))
A python program to show the usage of for loop to retrieve elements of
dictionaries

colors={‘r’: “Red”, ‘g’: “Green”, ‘b’: “Blue”, ‘w’: “white”}


for k in colors:
print(k) # r g b w
for k in colors:
print(colors[k]) #red green blue white
for k,v in colors.items():
print(‘key={} value={}’.format(k,v))
Looping in Dictionaries:
courses={‘DAA’: ‘CS’, ‘AOA’: ‘ME’, ‘SVY’: ‘CE’}
#iterate over key-value pairs
for k,v in courses.items():
print(k,v)
#iterate over keys
for k in courses.key():
print(k)
#iterate over keys-shorter way
for k in courses:
print(k)
#iterate over values
for v in courses.values():
print(v)
Operations on Dictionaries:
1. Concatenation--- doesn’t work
2. Merging– Doesn’t work
3. Comparison—Doesn’t work
4. Conversion—works
5. Cloning—works
6. Identity—works
7. Emptiness-Works
8. Aliasing—works
9. Searching—works
Built-in Functions on Dictionaries
d={10:’kvk’, 20:’kvs’, 30:’nani’, 40:’sunny’}
len(d) #returns number of key-value pairs
max(d) #returns maximum key in dictionary d
min(d) #returns minimum key in dictionary d
sorted(d) #returns sorted list of keys
sum(d) #returns sum of all keys if keys are numbers
any(d) #returns True if any key of dictionary d is True
all(d) #returns True if all keys of
reversed(d) #can be used for reversing dict/keys/values
Dictionary Comprehension:
General form of a dictionary comprehension is as follows:
dict_var ={ key:value for (key,value) in dictionary.items()}
Examples of dictionary comprehension:
d={‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4}
#obtain dictionary with each value cubed
d1={k: v**3 for (k,v) in d.items()}
print(d1)
#obtain dictionary with each value cubed if value>3
d2={k: v**3 for (k,v) in d.items() if v>3}
print(d2)
#identify odd and even entries in the dictionary
d3={k: (‘Even’ if v %2 == 0 else ‘Odd’) for (k,v) in d.items()}
print(d3)
What are Sets?
Sets are like lists, with an exception that they do not contain duplicate
entries
a=set() #empty set, use () instead of { }
b={20} # set with one item
c={‘kvk’, 25, 35455.00} #set with multiple items
d={10,10,10,10} #only one 10 gets stored

While storing an element in a set, its hash value is computed using a


hashing technique to determine where it should be stored in the set.
It is possible to create a set of strings and tuples, but not a set of lists.
s1={‘Morning’, ‘Evening’} #works
s2={(12,23),(15,25),(17,34)} #works
S3={[12,23],[15,25],[17,34]} #error

Since strings and tuples are immutable, their hash value remains same at
all times. Hence a set of strings or tuples is permitted. However, a list
may change, so its hash value may change, hence set of lists are not
permitted.

Sets are commonly used for eliminating duplicate entries.


Accessing set elements
Entire set can be printed by just using the name of the set. Set is an
unordered collection. Hence order of insertion is not same as the order
of access

s={15,25,35,45,55}
print(s) #prints {15,25,35,45,55}

Being an unordered collection, items in a set cannot be accessed using


indices.
Looping in sets:
Like strings, lists and tuples, sets too can iterated over using a for loop
s={12,15,13,23,22,16,17}
for ele in s:
print(ele)

Note that unlike a string, list or tuple, a while loop should not be used to
access the set elements. This is because we cannot access a set element
using an index, as in s[i].
Basic Set Operations:
Sets are like mutable. Their contents can be changed.

s={‘gate’,’fate’,’late’}
s.add(‘rate’) # adds one more elements to set s

If we want an immutable set, we should use a frozenset


s=frozenset({‘gate’,’fate’,’late’})
s.add(‘rate’) #error
Basic Set Operations:
Concatenation--- doesn’t work
Merging– Doesn’t work
Conversion--- works
Aliasing– works
Cloning-works
Searching—works
Identity– works
Comparison– works
Emptiness-- works
Two sets cannot be concatenated using +
Two sets cannot be merged using the form z = s+t
While converting a set using set(), repetitions are eliminated.
lst=[10,20,10,30,40,50,30]
s=set(list)
Using Built-in functions on sets:
Many built-in functions can be used with sets
s={10,20,30,40,50}
len(s) #return number of items in set s
max(s) # return maximum element in set s
min(s) #return minimum element in set s
sorted(s) #return sorted list(not sorted set)
sum(s) # returns sum of all elements in set s
any(t) # returns True if any element of s is True
all(t) # returns True if all elements of s are True
Set methods
Any set is an object of type set. Its methods can be accessed using the
syntax s.method(). Usage of commonly used set methods are shown
below:
s={12,15,13,23,22,16,17}
t={‘A’,’B’,’C’}
u=set()
s.add(‘Hello’) # adds ‘Hello’ to s
s.update(t) #adds element of t to s
u=s.copy()
s.remove(15) # delete 15 from s
s.remove(101) # would raise error, as 101 is not a member of s
s.discard(12) # remove 12 from 2
s.discard(101) # won’t raise an error, though 101 is not in s
s.clear() #removes all elements
Following methods can be used on 2 sets to check the relationship
between them:
s={12,15,13,23,22,16,17}
t={13,15,22}
print(s.issuperset(t)) # print True
print(s.issubset(t)) # prints False
print(s.isdisjoint(t)) #prints False
Mathematical set operations:
Following union, intersection and difference operations can be carried
out on sets:
engineers={‘Vijay’, ‘Sanjay’, ‘Ajay’, ‘Sujay’, ‘Dinesh’}
managers={‘Aditya’,’Dinesh’}
#union
print(engineers|managers)
#intersection
print(engineers&managers)
#difference
print(engineers-managers)
print(managers-engineers)
#symmetric difference--- managers who are not engineers
#and engineers who are not managers
print(managers^engineers)
OOPS
Features of Object Oriented Programming Systems(OOPS)
1. Classes and Objects
2. Encapsulation
3. Abstraction
4. Inheritance
5. Polymorphism

You might also like