Social Media

Image Slider

1/14/2019

Methods related to dictionary data structure

del() method: This method is used to delete any item from the dictionary.
d={1:"mayank",2:"aniket",3:"prajapati"}
del(d[1])
print(d) # {2: 'aniket', 3: 'prajapati'}


clear() method: This function is used to delete all the values from the dictionary and our dictionary will be emptied after executing this function.
d={1:"mayank",2:"aniket",3:"prajapati"}
d.clear()
print(d) # {}


copy() function: This function is used to copy all the items of dictionary into another object.
d={1:"mayank",2:"aniket",3:"prajapati"}
e=d.copy()
print(e) # {1:"mayank",2:"aniket",3:"prajapati"}


pop(): This function will take key as an argument. This function will only return value not the item.
d={1:"mayank",2:"aniket",3:"prajapati"}
x=d.pop(1)
print(x) # "mayank"

print(d) # {2:"aniket",3:"prajapati"}

popitem(): This function does not require any argument. It will randomly remove an item from the dictionary and return that item as a tuple.
d={1:"mayank",2:"aniket",3:"prajapati"}
x=d.popitem()

print(type(x)) # tuple
print(x) # (3, 'prajapati')
print(d) # {1:"mayank",2:"aniket"}




1/10/2019

Introduction to dictionary

Dictionary concept is used for association purpose.
We use dictionary data structure when there is an association required between two objects.
Values are stored pairwise in dictionary in the form of keys and values.
Key act as primary key (keys cannot be repeated).
Value repetition can be possible in dictionary data structure.
The nature of key and values can be heterogeneous.
Indexing and slicing cannot be used in dictionary.
There is no specific order for storing elements in the dictionary.
Dictionary is mutable data structure.
We can use add, delete and update methods in dictionary data structure.
Dictionary is denoted using {}.

How to create an empty dictionary??
d={}
print(type(d)) #<class 'dict'>
Empty dictionary can also be created using dict() method as shown below.
d=dict()

Storing values in dictionary:
d={1:"Mayank",2:"Aniket",3:"Prajapati"}
print(d)


Accessing elements of dictionary:
We can access the element of dictionary using for loop as shown below.
d={1:"mayank",2:"aniket",3:"prajapati"}
for x in d:
    print(d[x],end=" ")

Output: mayank aniket prajapati



Accessing specific element using key in dictionary:
 d={1:"mayank",2:"aniket",3:"prajapati"}
print(d[2]) # aniket
print(d[4]) # KeyError
1/09/2019

pop, discard, remove methods of Set Data Structure

pop() function: This function will remove any random element from the set.
It will return that element which is removed by it.
If set is empty this function will give error (KeyError).
s1={1,2,3,4}
s1.pop()
print(s1) # {2,3,4}

discard() function: This function will remove the specified element from the set.
The return type of this function is None.
s1={1,2,3,4}
s1.discard(2)
print(s1) # {1,3,4}

There is no error come if the specified element is not present in the set or if the set is empty.

remove() function: The return type of this function is None.
It will give error (KeyError) if the specified element is not present in the set or if the set is empty.
s1={1,2,4}
s1.remove(2)
print(s1) # {1,4}

copy() function: This function is used to copy whole data of one set to other set object.
s1={1,3,4}
s2=s1.copy()
print(s2) # {1,3,4}

Note** List cannot be an element of set.
Tuple can be an element of set.



1/08/2019

Methods related to Set

add(): This method is used to add any new value to set data structure.
s={1,2,3}
print(id(s))
s.add(4)
print(s)
print(id(s))


Both id will be same, this proves that set is mutable data structure.

update() function: This function actually useful when we want to add all the elements of a sequence or more than one sequence into a single set.
s={1,2,3}
s.update([4,5])
print(s) # {1,2,3,4,5}

We can also pass more than one sequence in the update method.
s={1,2,3}
l1=[1,4,5]
l2=[6]
s.update(l1,l2)
print(s) # {1,2,3,4,5,6}


intersection() method: The return type of intersection method is a set. The simple example of usage of intersection method is given below.
s1={1,2,3}
s2={3,4,5}
s3=s1.intersection(s2)
print(s3) # {3}


union() method: As suggested by the name it will perform union operation between the two sets. Its return type is also a set.
s1={1,2,3}
s2={4,5,6}
s3=s1.union(s2)
print(s3) # {1,2,3,4,5,6} 


issubset() method: This function will tells us whether a given set is a subset of targeted set or not. Its return type is boolean.
s1={1,2,3}
s2={1,2}
print(s2.issubset(s1)) # True


issuperset() function: This method will tells us whether a given set is a superset of targeted set or  not. Its return type is also boolean.
s1={1,2,3}
s2={1,2}
print(s1.issuperset(s2)) # True



clear() function: This function is used to remove all the elements from the set data structure, means it will empty the targeted set.
s={1,2,3}
s.clear()
print(s) #set()


1/04/2019

Set Introduction

Set is a data structure in Python which is denoted by {}.
Duplicate values are not allowed in set.
We cannot use indexing and slicing here.
It is mutable data structure.

Creation of empty set:
s=set()
print(type(s)) # set
Note* s={} is not empty set. It is dictionary.

Set does not preserve any sequence of storing data elements.
s=set("mayank")
print(s) # {'n', 'm', 'a', 'y', 'k'}

Set can only take sequence as argument.
s=set([1,2,2,3,4]) # 2 will store only once as repetition is not allowed here. 
print(s) # {2,1,4,3}






1/03/2019

Some methods related to tuple data structure:

max() and min(): These functions are used to calculate the max and minimum element from the tuple.
t=(1,2,3)
print(max(t)) # 3
print(min(t)) # 1

sum() function: This function is used to calculate the sum of all the elements of the tuple
t=(1,2,3)
print(sum(t)) # 6

len() : This function is used to calculate the length of the tuple.
t=[1,2,3,3,4]
print(len(t)) # 5

Accessing element of tuple using for loop:
We can access elements of tuple using for and while loop.
t=(1,2,3)
for x in t:
    print(x)

Accessing elements of tuple using while loop:
t=(1,2,4,4)
l=len(t)
i=0
while i<l:
    print(t[i])
    i+=1

Taking tuple from user:
t=tuple([eval(x) for x in input().split()])
Note: If we are giving string input here we have to use quotes in the input as well.

If we wan to store only integer in the tuple then we can do like this.
t=tuple([int(x) for x in input().split()])
print(t)

We can also use map() function for this purpose.
t=tuple(map(int,input().split()))
print(t)



Introduction to tuple data structure

Tuple is a sequential data structure.
As string and list tuple also support indexing and slicing.
The elements of tuple can be heterogeneous in nature.
Tuple is immutable data structure.
We have to use () to defining the tuple.
We cannot use append() method in tuple because it is immutable data structure.
example
t=(1,2,3,4)
print(type(t)) #tuple

Creating an empty tuple:
tuple() method can be used to create an empty tuple.
t=tuple()
print(type(t)) # tuple

Creating a tuple with single element:
t=(1,) # , is necessary if we are creating a tuple of single element, otherwise it will be int type.

Conversion of list into tuple:
We can also convert list data structure into tuple as shown below.
l=[1,2,3,4,5]
t=tuple(l)
print(t) # (1, 2, 3, 4, 5)


Problems on String

Problem1: Check whether the string entered by the user is palindrome or not.
s=input()
if s==s[len(s)::-1]:
    print("Palindrome")
else:
    print("Not palindrome")

Problem2: Write script to count the number of lower case letters in Python.
s=input()
count=0
for x in s:
    if x.islower():
        count+=1
print("Number of lower case letters are",count)

Problem3: Write an script to count the number of digits in a given string.
s=input()
count=0
for x in s:
    if x.isdigit():
        count+=1
print("Number of digits are",count)

1/02/2019

More functions of String

list(): String can be converted to list using list() method.
s="mayank kumar"
l=list(s)
print(l) # ['m', 'a', 'y', 'a', 'n', 'k', ' ', 'k', 'u', 'm', 'a', 'r']

isalnum(): This function returns True if all the characters of string are A-Z, a-z or 0 to 9, else return False.
s="sm32"
print(s.isalnum()) #True

isdigit(): This function returns True if all the characters of string are 0 to 9.
s="0383m"
print(s.isdigit()) # False

isalpha(): This function returns True if all the characters of the string are A -Z or a-z.
s="mayank"
print(s.isalpha()) # True

isupper(): This function returns True if all the letters of string are in capital letters.
s="MAYANK"
print(s.isupper()) #True

islower(): This function returns True if all the letters in the string are in lower case.
s="mayank"
print(s.islower()) # True

Functions Related to string

len() method: This function is similar to the len() function we have used in case of list data structure.
This will give us the length of the string.
s="mayank"
print(len(s)) #6

upper() method: This method is used to convert all characters of string into uppercase. The original string is not affected by this method.
s1="mayank"
s2=s1.upper()
print(s1) #mayank
print(s2) # MAYANK

lower() method: It converts all the characters of string into lower case. It is similar to upper() method and does not affect the original string.
s1="Mayank"
s2=s1.lower()
print(s1) #Mayank
print(s2) # mayank

startswith() and endswith() method: This method returns True or False. If the string starts with the supplied sequence it will return True otherwise return False.
s="Mayank"
s.startswith("Ma") #True
Similarly ends with check the ending of the string with given sequence.
s.endswith("an") #False

split() function: The return type of this function is a list. String is separated on the basis of given character. This character will not be included in the final list.
s="mayank kumar prajpati"
l=s.split(" ")
print(l) #["mayank","kumar","prajapati"]



Introduction To String

String is a sequential data structure.
Indexing and slicing is supported by String.
It is immutable.
String also support negative indexing. Negative indexing start from -1 in the last.
example:
s="Mayank"
print(s,type(s)) # Mayank <class 'str'>
print(s[-2]) # n

How to take string from user??
String can simply be taken from user using input() function.
s=input()
print(s)
String also support concatenation. Means we can concatenate a string to another string also.
s="Mayank"
print(id(s)) 
s+="Prajapati"
print(id(s))
Both will print different id which shows that string is immutable data structure.

Conversion of list into string:
We can convert a whole list into a string. This can be done simply using the join method. A simple script which will illustrate this concept is given below:
l=["mayank", "kumar", "prajapati"]
s=" ".join(l)
print(s) # mayank kumar prajapati

Taking list from user

There can be many ways to take the list from the user.]
1. Taking element one by one and append it in  the list
l=list()
n=int(input("enter number of elements : "))
for i in range(n):
    x=input()
    l.append(x)
print(l)

2. Using map() function:
l=list(map(int,input().split()))
This function converts the value entered by the user and append it into the list one by one.
split() function tells us where inputs end. By default it is space. After space character next input is counted.

3. Using for loop in single line:
l=[int(x) for x in input().split()]

4. Using eval() function:
l=eval(input("Enter the list"))   #[1,2,3]
print(l)
   


1/01/2019

append,pop and remove function in List

append() function:
This function is used to append any value at the end of the list.
eg
l=[1,2,3]
l.append(4)
print(l) # [1,2,3,4]

pop() function:
It deletes the last value of the list by default.
It returns the value which is deleted  by this method.
It raises IndexError if no element found.
l=[10,20,30]
x=l.pop()
print("The deleted element is",x)
print(l)  # [10,20]
pop function can also be used to delete any specific value from the list as shown below.
l=[1,2,3]
l.pop(2) #here 2 is the index means 3 will be deleted from the list
print(l) # [1,2]

remove() function:
This function does not return the value it has removed from the list.
It always requires an argument.
It raises ValueError if element is not found in the list.
l=[1,2,3]
l.remove(2)
print(l) # [1,3]


Some useful Functions of List data structure

There are some most important functions of list data structure which we can use in our script without knowing the internal structure of the functions.

len() function: This function will give us the length of the list.
l=[1,2,"mayank",3]
x=len(l)
print(x) # 4

index(): This method is used to find out the index of any element in the list.
The usage of this function can be as:
l=list()
l=[1,2,3,4,5]
print(l.index(3)) #2
index() method gives IndexError if we have not supplied a right index to this function.

Another usage of index() method is as:
l=[1,2,3,4]
i=l.index(2,3) # will start find index of two and searching will start from index 3
print(i)  # gives ValueError

reverse() function:  This function will reverse the element of the whole list.
l=[1,2,3]
l.reverse()
print(l) # [3,2,1]

sort() function: This method is used to sort the given list.
l=[2,5,1,4,6,2]
l.sort()
print(l) # [1,2,2,4,5,6]

clear() function: This function is used to delete all elements from the list.
The usage of this function is as follows:
l=[1,2,3,4]
l.clear()
print(l) #[]

max() function: This function returns the maximum value from the given list.
A simple script to demonstrate this function is as:
l=[2,3,5,2,6,6,4]
m=max(l)
print(m) #6

min() function: This function returns the maximum element from the list.
The script can be as:
l=[1,2,,5,2,5]
m=min(l)
print(m) #1

sum() function: This method returns the sum of all values present in the list.
example:
l=[1,2,3,4]
s=sum(l)
print(s) #10


List Introduction

List:
List is a data structure in Python which is very similar to arrays in C.
The difference between array and list is that array can able to store only homogeneous elements while in list we can have non homogeneous elements also.
List is a iterative and sequential data structure.
Indexing and slicing is possible in case of list data structure.
List are denoted by [].
Duplicates values are allowed in list data structure.
Creation of empty list::
If we want to create an empty list then we can do this in two ways. These are given below:
l=[]  # empty list
l=list()  # empty list

Initializing the list:
l=[1,2,3,4]
print(l[2])  # 3

Printing whole list:
We can print the all elements of list in two ways.
print(l)

Using for loop

for x in l:
     print(x) 

Editing values of List:

l=[1,2,4]
print(l[0])  # 1
l[0]=8
print(l[0])  # 8