PWP Unit 3 notes
PWP Unit 3 notes
Tuples: Tuple is a collection of elements and it is similar to the list. But the items of the tuples
are separated by comma and the elements are enclosed in () parenthesis.
Examples of tuples:
T1=(10,20,30,40)
T2=(‘a’, ‘b’, ‘c’, ‘d’)
T3=(‘A’,10,20)
T4=(‘aaa’, ‘bbb’, 30,40)
The empty tuple can be created as
T1=()
The tuple index starts at 0.
Example:
>>>t1=(10,20, ‘AAA’, ‘BBB’)
>>>print(t1[0])
10
>>>print(t1[1:3])
(20, ‘AAA’)
Use of tuple(): There is built in function tuple which is used to create the tuple.
>>>t1=tuple()
>>>print(t1)
()
>>>t1=tuple(‘hello’)
>>>print(t1)
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)
Comparing Tuples: The tuples can be compared using relational operators. Tuples are
compared position by position. The first item of first tuples is compared to the first item of
second tuple; if they are not equal, this is the result of the comparison, and else the second item
is considered, then the third and so on.
For example:
>>>(4,2)<(3.5)
False
>>>(4,2)<(5,5)
True
Tuple Assignments: we can create a tuple by using assignment operator. Multiple assignments
are possible at a time using tuple assignment.
Example:
>>>a,b=10,20
>>>print(a)
10
>>>print(b)
20
Here the left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable.
Split Function: we can also separate out the values in the expression in the tuple by using split
function.
>>>student=’AAA,123’
>>>name,roll=student.split(‘,’)
>>>print(name)
AAA
>>>print(roll)
123
Tuples are Immutable: Tuple is said to immutable. That means once created we cannot change
the tuple.
>>>T1=(10,20,30,40)
>>>Print(T1)
(10,20,30,40)
>>>T1[1]=100
TypeError: 'tuple' object does not support item assignment
Hence tuple are immutable.
Updating Tuple: Tuple are immutable. That means –values in the tuple cannot be changed. We
can only extract the values of one tuple to create another tuple.
>>>T1=(10,20,30)
>>>T2=(40,50)
>>>T3=T1+T2
>>>Print(T3)
(10,20,30,40,50)
Lists: It is basically an ordered sequence of some data written using square brackets ([ ]) and
commas (,).
The values in the list are called elements or items.
Example.
T1=[10,20,30,40] #list of integers
T2=[‘aaa’, ‘bbb’, ‘ccc’] #list of strings
T3=[‘a’, 10,20, ‘b’] #Mixed list
T4=[10,20,[‘a’, ‘b’, ‘c’]) #nested list( The list within another list is called nested list.
T5=[] #Empty list (The list that contains no element is called empty list)
List are Mutable: It is possible to change the values of list. If the bracket operator is present on
the left hand side, then that element is identified and the list element is modified accordingly.
>>>a=[‘AAA’, ‘BBB’, ‘CCC’]
>>>a[1]= ‘XXX’
>>>print(a)
[‘AAA’, ‘XXX’, ‘CCC’]
IN Operator: Using the in operator we can check whether particular element belongs to the list
or not.
If the given element is present in the list it returns true otherwise false.
>>>a=[‘AAA’, ‘XXX’, ‘CCC’]
>>> ‘XXX’ in a
True
>>> ‘BBB’ in a
False
>>>a=[10,20,30,40]
>>>for i in range(len(a)):
>>>a[i]=a[i]+1
>>>print(a)
[11, 21, 31, 41]
2) Using enumerate () function: We can print both index and item of the list.
a=[10,20,30]
for i in enumerate(a):
print(i)
output:
(0,10)
(1,20)
(2,30)
List Operations: There are two operations that can be performed using operators such as + and
*.
1. Concatenation using +: The two lists can be created and can be joined using + operator.
>>>L1=[10,20,30]
>>>L2=[40,50,60]
>>>L3=L1+L2
>>>print(L3)
Output:
[10,20,30,40,50,60]
2. Repetition using * : The * used to repeat the list for number of times.
>>>[10,20,30]*3
Output:
[10,20,30,10,20,30,10,20,30]
List Slices: The: operator used within the square bracket that it is a list slice and not the index of
the list.
>>>a=[10,20,30,40,50,60]
>>>a[1:4]
[20,30,40]
If we omit the first index then the list is considered from the beginning.
>>>a[:5]
[10,20,30,40,50]
If we omit the last second index then slice goes to end.
>>>a[4:]
[50,60]
If we omit both the first and second index then the list will be displayed from beginning to end.
>>>a[:]
[10,20,30,40,50,60]
List Methods:
1) Append: It adds the element at the end of the list.
>>>a=[10,20,30]
>>>a.append (40)
>>>print(a)
Output:
[10,20,30,40]
Output:
[‘A’, ‘B’, ‘C’, ‘D’]
2. Extend: It takes the list as an argument and appends this list at the end of old list.
>>>a=[10,20,30]
>>>b=[‘a’, ‘b’, ‘c’]
>>>a.extend(b)
>>>print(a)
Output:
[10, 20, 30, ‘a’, ‘b’, ‘c’]
Output:
[‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’]
Deleting Elements: The deletion of any element from the list is carried out using functions like
pop, remove and del.
POP Function: If we know the index of the element to be deleted then just pass that index as an
argument to pop function.
>>>a=[10,20,30,40]
>>>val=a.pop(1)
>>>print(a)
Output:
[10,30,40]
If we do not provide any argument to the pop function then the last element of the list will be
deleted.
>>>a=[10,20,30,40]
>>>val=a.pop()
>>>print(a)
Output:
[10,20,30]
Remove function: if we know the value of the element to be deleted then the remove function is
used.
>>>a=[10,20,30,40]
>>>a.remove(20)
>>>print(a)
Output:
[10,30,40]
Del Function: It is possible to remove more than one element at a time using del function.
>>>a=[10,20,30,40,50]
>>>del a[2:4]
>>>print(a)
Output:
[10,20,40]
List Functions:
1. len(): This function returns the length of the string.
>>> a=[10,20,30,40,50]
>>> b=len(a)
>>> print(b)
5
2. max(): This function returns maximum element present in the list.
>>> a=[10,20,30,40,50]
>>> b=max(a)
>>> print(b)
50
3. min():This function returns minimum element present in the list.
>>> a=[10,20,30,40,50]
>>> b=max(a)
>>> print(b)
10
4. Sum(): This function returns the sum of all the elements in the list.
>>> a=[10,20,30,40,50]
>>> b=sum(a)
>>> print(b)
150
5. Sort(): This function returns a list which is sorted one.
>>> a=[50,30,20,40,10]
>>> a.sort()
>>> print(a)
[10, 20, 30, 40, 50]
>>> str='hello'
>>> a=list(str)
>>> print(a)
['h', 'e', 'l', 'l', 'o']
2. Split Function: if the strings contains multiple words then we need to use built in function
split to split the words into the list.
>>> a="I Love Python Programming Very much"
>>> b=a.split()
>>> print(b)
['I', 'Love', 'Python', 'Programming', 'Very', 'much']
3. Join Function: It exactly reverse to the split function. It takes the list of strings and
concatenate to form a string.
>>> a=['I', 'Love', 'Python', 'Programming', 'Very', 'much']
>>> ch=(' ')
>>> ch.join(a)
'I Love Python Programming Very much'
List Comprehensions: It is used to create and define new lists using existing lists.
Example: Write a python program to create a list of even numbers from 0 to 10.
even=[]
for i in range(1,11):
if i%2==0:
even.append(i)
print("Even number list is:",even)
output:
Even number list is: [2, 4, 6, 8, 10]
Example: Write a python program to create a list of odd numbers from 0 to 10.
odd=[]
for i in range(1,11):
if i%2!=0:
odd.append(i)
print("Even number list is:",odd)
output:
odd number list is: [1, 3, 5, 7, 9]
Dictionary: dictionary is ordered collection of items. These items are in the form of key- value
pairs.
The dictionary contains the collection of indices called keys and collection of values.
Each key is associated with a single value.
Creating dictionary:
A = {1:'red',2:'blue',3:'yellow'}
Print (A)
2. Remove item from dictionary: For removing an item from the dictionary we use the
keyword del.
3. Updating the value of the dictionary: we can update the value of the dictionary by
directly assigning the value to corresponding key position.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> a[2]='pink'
>>> print(a)
{1: 'red', 2: 'pink', 3: 'black', 4: 'yellow'}
4. Checking length: the len() function gives the number of pairs in the dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> len(a)
4
Dictionary Methods:
1. The Clear method: This method remove all the items from dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> a.clear()
>>> print(a)
{}
2. The copy method: The copy method returns the copy of the dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> b=a.copy()
>>> print(b)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
3. The fromkey method: It creates a new dictionary from the given sequence of elements
with a value provided by the user.
>>> keys={10,20,30}
>>> values='number'
>>> a=dict.fromkeys(keys,values)
>>> print(a)
{10: 'number', 20: 'number', 30: 'number'}
4. The get method: It returns the value for the specified key if the key is in dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a.get(1))
red
>>> print(a.get(2))
blue
>>> print(a.get(3))
black
>>> print(a.get(4))
yellow
5. The Value Method: It display the list of values present in the dictionary.
>>> a={1:'red',2:'blue',3:'yellow',4:'black'}
>>> print(a.values())
dict_values(['red', 'blue', 'yellow', 'black'])
6. The POP Method: It removes an element from dictionary having the given key.
>>> a={1:'red',2:'blue',3:'yellow',4:'black'}
>>> a.pop(2)
'blue'
>>> print(a)
{1: 'red', 3: 'yellow', 4: 'black'}
output:
{'j': 2, 'o': 1, 'h': 1, 'n': 2, 'y': 1, '-': 1, 'u': 1, 'm': 1, 'p': 1}
Looping and Dictionaries:- For iterating through the dictionary we can use for loop.
The corresponding key and values present in the dictionary can be displayed using for loop.
a={1:'red',2:'blue',3:'yellow',4:'black'}
for i in a:
print(i,a[i])
output:
1 red
2 blue
3 yellow
4 black
Output:
1 red
2 blue
3 yellow
4 black
Sets in Python
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
Output
{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'
Creating an empty set is a bit tricky.
Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements, we use the set() function without any argument.
# initialize a with {}
a = {}
Output
<class 'dict'>
<class 'set'>
# initialize my_set
my_set = {1, 3}
print(my_set)
# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
Output
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
Removing elements from a set
A particular item can be removed from a set using the
methods discard() and remove().
The only difference between the two is that the discard() function leaves a set
unchanged if the element is not present in the set. On the other hand,
the remove() function will raise an error in such a condition (if element is not
present in the set).
The following example will illustrate this.
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
Output
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2
Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item
will be popped. It is completely arbitrary.
We can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)
Output
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}
Try the following examples on Python shell.
Set Intersection
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using
the intersection() method.
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Output
{4, 5}
Set Difference
Difference of the set B from set A(A - B) is a set of elements that are only
in A but not in B. Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using
the difference() method.
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Output
{1, 2, 3}
# use - operator on B
>>> B - A
{8, 6, 7}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Output
{1, 2, 3, 6, 7, 8}
Method Description
update() Updates the set with the union of itself and others