In python series II , we will be focus on following tutorials-
Tutorial-10 ---> Python Sets.
Tutorial-11 ---> Python Dictionaries
Tutorial-12 ---> Slice function
Tutorial-13 ---> Python While loop
Tutorial-14 ---> Python For loop
Tutorial – 10
Python Sets:
Sets is an unordered collection with no duplicate elements and no indexing. We define elements in sets in curly brackets {}. Each value in set must be a unique value.
>>> A = {1,2,5,4,7,9}
Suppose we define set with duplicate value-
>>> A = {1,2,5,4,7,9,2}
>>> A
{1,2,4,5,7,9}
It going to delete duplicate values and save only unique values.
Lets see some of methods related to sets-
>>> len(A) #length of set
6
>>> A.add(10)
>>> A
{1,2,4,5,7,9,10}
In above case '10' is added only when it is not in set.If it is already their nothing will happen.
>>> A.add(10)
>>> A
{1,2,4,5,7,9,10}
To add multiple values in a set-
>>> A.update([15,18,17,14])
>>> A
{1,2,4,5,7,9,10,14,15,17,18}
To remove values from set-
>>> A.remove(18)
>>> A
{1,2,4,5,7,9,10,14,15,17}
>>> A.discard(17)
>>> A
{1,2,4,5,7,9,10,14,15}
>>>A.remove(100)
KeyError:100
It gives error when element is not their in set.
>>> A.discard(100)
'discard' dont give error.
>>> A.pop()
It removes any random value from set.
We can clear set-
>>> name = {'max','tom','den'}
>>> name.clear()
>>> name
set()
It means empty set with no value.
We can delete set-
>>> del name
>>> name
NameError: name'name' is not defined.
We can create set in other ways also-
>>> name = set(('max','tom','den'))
>>> name
{'tom','max','den'}
We can convert list into set-
>>> z = set([1,2,3,5])
>>> z
{1,2,3,5}
We can use mathematical set operations on python set-
>>> A = {2,4,5,7,9,10,14,15}
>>> B = {10,11,12,13,14,16,18}
>>> A\B # A union B
{2,4,5,7,9,10,11,12,13,14,15,16,18}
We can also find union-
>>> A.union(B)
{2,4,5,7,9,10,11,12,13,14,15,16,18}
To find out intersection between two sets-
>>> A & B #A intersection B
{10,14}
We can also find intersection-
>>> A.intersection(B)
{10,14}
To find out difference between two sets-
>>> A-B
{2,4,5,7,9,15}
>>> B-A
{16,18,11,12,13}
We can also find out difference in other way-
>>> A.difference(B)
{2,4,5,7,9,15}
>>> B.difference(A)
{16,18,11,12,13}
Symmetric difference between two sets contains all elements that are either in set 'A' but not in set 'B' or their in set 'B' but not in set 'A'.
>>> A^B
{2,4,5,7,9,11,12,13,15,16,18}
>>> B^A
{2,4,5,7,9,11,12,13,15,16,18}
We can also find out symmetric difference-
>>> A.symmetric_difference(B)
{2,4,5,7,9,11,12,13,15,16,18}
Sets are not indexed or ordered.
>>> A[0]
TypeError:'set' object does not support indexing.
>>> dir(A)
It prints all methods which we can use in sets.
Tutorial – 11
Python Dictionaries:
Dictionaries in python are like associative lists or a map. It can also be defined as a list of pairs.
>>> D = {'name':'max','age':14,'year':2004}
>>> D
{'name':'max','year':2004,'age':14}
Here name,year & age are keys and max,2004 & 14 are values.
We can access the values in dictionaries based on their keys.
>>> D['name']
'max'
>>> D['age']
14
We can use string, integer, decimal, boolean & tupple as keys.
>>> E = {'name':'tom', 15:15, 15.1:15.1, True:True, (2,3):5}
>>> E[(2,3)]
5
>>> E[True]
True
>>> E[15]
15
>>> E[100]
KeyError:100
The above key is not present in dictionary.
To find the no. of items in dictionary-
>>> len(E)
5
>>> D.get('name')
'max'
To add key value pair-
>>> D['Surname'] = 'Tesar'
>>> D
{'name':'max','year':2004,'Surname':'Tesar', 'age':14}
To remove any key value pair-
>>> D.pop('Surname')
'Tesar'
>>> D
{'name':'max','year':2004,'age':14}
To clear values inside dictionaries-
>>> E
{True:True, 'name':'tom', 15.1:15.1, (2,3):5, 15:15}
>>> E.clear()
>>> E
{}
It will give empty dictionary.
To delete dictionary-
>>> del E
>>> E
NameError: name 'E' is not defined.
>>> D
{'name':'max','year':2004,'age':14}
To update name-
>>> D['name'] = 'tom'
>>> D
{'name':'tom','year':2004,'age':14}
>>> D.update({'name':'max'})
>>> D
{'name':'max','year':2004,'age':14}
To list out all keys of particular dictionary-
>>> D.keys()
dict_keys(['name', 'year', 'age'])
Similarly to list out all values of particular dictionary-
>>> D.values()
dict_values(['max',2004, 14])
To list out all key value pairs-
>>> D.items()
dict_items([('name','max'), ('year',2004), ('age',14)])
To remove last key value pair which is added or updated-
>>> D
{'name':'max','year':2004,'age':14}
>>> D.popitem()
('name','max')
>>> D
{'year':2004,'age':14}
Since name is updated above ('tom' to 'max')
Tutorial – 12
Slice function in python:
We use slice function to slice something out of the collection. To use slice function-
x = slice(start:end)
Here items start through end-1
x = slice(start,end,step)
Lets take an example-
>>> a = [0,1,2,3,4,5,6,7,8,9] #list
>>> b = (0,1,2,3,4,5,6,7,8,9) #tupple
>>> c = ‘012356789’ #string
>>> x = slice (0,5)
>>> a[x]
[0,1,2,3,4]
>>> a[0:5]
[0,1,2,3,4]
>>> b[4:]
(4,5,6,7,8,9)
>>> b[:6]
(0,1,2,3,4,5)
>>> c[:]
‘0123456789’
>>> c[0:5]
‘01234’
>>> a
[0,1,2,3,4,5,6,7,8,9]
>>> a[0:9:2]
[0,2,4,6,8]
>>> a[0:9:3]
[0,3,6]
>>> a[0:9:4]
[0,4,8]
>>> a[::4]
[0,4,8]
Negative numbers:
We can give index in negative numbers also-
| p | y | t | h | o | n |
Positive index- 0 1 2 3 4 5
Negative index- -6 -5 -4 -3 -2 -1
Similarly for string '0123456789'-
>>> c[-1]
‘9’
>>> c[-2]
‘8’
>>> c[-3]
‘7’
>>> a
[0,1,2,3,4,5,6,7,8,9]
>>> a[::-1]
[9,8,7,6,5,4,3,2,1,0]
>>> a[1::-1]
[1,0]
>>> a[:-3:-1]
[9,8]
>>> a[-3::-1]
[7,6,5,4,3,2,1,0]
Tutorial – 13
Python While loop:
A loop allows us to repaeat over some block of code again & again until and unless some condition is met. Lets take an example-
i = 0
While i<5:
print(“the value of i is :”,i)
i = i + 1 # i += 1
print(“finished while loop”)
Now we see the output of above code:
The value of i is : 0
The value of i is : 1
The value of i is : 2
The value of i is : 3
The value of i is : 4
finished while loop
Let’s take another example-
num = 1
sum = 0
print(“enter a number.Please enter zero(0) to exit”)
while num != 0:
num = float(input("number ? "))
sum = sum + num;
print(“sum=”,sum)
else:
print(“finished sum”)
i = 0
While i<5:
print(“the value of i is :”,i)
i = i+1 # i += 1
else:
print(“finished while loop”)
On executing above code-
enter a number.Please enter zero(0) to exit
number ? 100
sum = 100.0
number ? 50
sum = 150.0
number ? 900
sum = 1050.0
number ? 0
sum = 1050.0
finished sum
the value of i is : 0
the value of i is : 1
the value of i is : 2
the value of i is : 3
the value of i is : 4
finished while loop
Tutorial – 14
Python for loop:
A for loop is used to iterate over a sequence and that sequence can be a list, a tuple/ a dictionary/ a set / a string. Lets take an example:
>>> A = [0,1,2,3,4,5] # list
>>> B = (0,1,2,3,4,5) # tuple
>>> C = {0,1,2,3,4,5} # set
>>> D = ‘012345’ # string
>>> E = { “name”: ‘max’ , ”age”: 20 } # dictionary
# Now we see how to use ‘in’ operator in python, because it is used in for loop.
# 'in' operator checks whether the given element is present in sequence or not. If it is present it gives 'true' otherwise 'false'.
>>> print(0 in A)
true
>>> print(100 in A)
false
>>> print(1 in B)
true
>>> print(1 in C)
true
>>> print(‘1’ in D)
true
How to use for loop in python:
We will apply ‘for’ loop step by step in list, tuple, set, string & dictionary.
# 'for' loop in list.
>>> for x in A:
print(x)
0
1
2
3
4
5
‘for’ loop is going to iterate over a list one by one and ‘in’ operator checks whether the element in in the list or not. When for loop starts, it transfers the first value ‘0’ into ‘x’ and it then checks whether ‘x’ is in list ‘A’ or not and then it print the value of ‘x’ i.e ‘0’. In same manner next value ‘1’ is transferred into x. And this iteration goes on and on until it reaches the last value i.e ‘5’
# 'for' loop in tuple.
>>> for x in B:
print(x)
0
1
2
3
4
5
# 'for' loop in set.
>>> for x in C:
print(x)
0
1
2
3
4
5
# 'for' loop in string.
>>> for x in D:
print(x)
0
1
2
3
4
5
# 'for' loop in dictionary.
>>> for x in E.keys() :
print(x)
age
name
>>> for x in E.values() :
print(x)
max
20
>>> for key,value in E.items() :
print(key, ' ', value)
name max
age 20
>>> for x in range(6) :
print(x)
0
1
2
3
4
5
>>> for x in range(2,6) :
print(x)
2
3
4
5
>>> for x in range(2,30,3) : # third value i.e 3 is step.
print(x)
2
5
8
11
14
17
20
23
26
29
We can also used ‘else’ statement with the ‘for’ loop. ‘else’ statement is executed when for loop is finished.
>>> for x in range(2,30,3) :
print(x)
else:
print(“finished”)
2
5
8
11
14
17
20
23
26
29
finished