Thursday, 26 December 2019

Python Datatypes

Python Datatypes

Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to a variable. For example;
a=5
Python supports 4 types of numeric data.
  1. int (signed integers like 10, 2, 29, etc.)
  2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
  3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
  4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)
Python allows us to use a lower-case L to be used with long integers. However, we must always use an upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts respectively).

String
The string can be defined as the sequence of characters represented in the quotation marks. In python, we can use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions and operators provided.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+" python" returns "hello python".


The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ".

List
List in python is implemented to store the sequence of various type of data. However, python contains six data types that are capable to store the sequences but the most common and reliable type is list.
A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets [].
Eg:
L1 = ["John", 102, "USA"]  
L2 = [1, 2, 3, 4, 5, 6]  
L3 = [1, "Ryan"]  
Lets consider a proper example to define a list and printing its values.
>>>Output
emp = ["John", 102, "USA"]   
Dep1 = ["CS",10];  
Dep2 = ["IT",11];  
HOD_CS = [10,"Mr. Holding"]  
HOD_IT = [11, "Mr. Bewon"]  
print("printing employee data...");  
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))  
print("printing departments...");  
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]));  
print("HOD Details ....");  
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]));  
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]));  
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT));  

printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>

List indexing and splitting
The indexing are processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on.
Consider the following example:
List = [0,1,2,3,4,5]
List[0] = 0 List[0:] = [0,1,2,3,4,5]
List[1] = 1 List[:] = [0,1,2,3,4,5]
List[2] = 2 List[2:4] = [2,3]
List[3] = 3 List[1:3] = [1,2]
List[4] = 4 List[:4] = [0,1,2,3]
List[5] = 5

Updating List values
Lists are the most versatile data structures in python since they are immutable and their values can be updated by using the slice and assignment operator.
Python also provide us the append() method which can be used to add values to the string.
Consider the following example to update the values inside the list.
List = [1, 2, 3, 4, 5, 6]   
print(List)   
List[2] = 10;  
print(List)  
List[1:3] = [89, 78]   
print(List)  
>>>Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we do not know which element is to be deleted from the list.
Consider the following example to delete the list elements.
List = [0,1,2,3,4]   
print(List)  
del List[0]  
print(List)   
del List[3]  
print(List)  
>>>Output:
[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3]
Python List Operations
The concatenation (+) and repetition (*) operator work in the same way as they were working with the strings.
Lets see how the list responds to various operators.

Consider a List l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8]
Operator
Description
Example
Repetition
The repetition operator enables the list elements to be repeated multiple times.
L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
Concatenation
It concatenates the list mentioned on either side of the operator.
l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
Membership
It returns true if a particular item exists in a particular list otherwise false.
print(2 in l1) prints True.
Iteration
The for loop is used to iterate over the list elements.
for i in l1:
    print(i)
Output
1
2
3
4
Length
It is used to get the length of the list
len(l1) = 4

Iterating a List

A list can be iterated by using a for - in loop. A simple list containing four strings can be iterated as follows.
Eg:
List = ["John", "David", "James", "Jonathan"]  
for i in List: #i will iterate over the elements of the List and contains each element in each iteration.   
    print(i);  
>>>Output:
John
David
James
Jonathan

Adding elements to the list
Python provides append() function by using which we can add an element to the list. However, the append() method can only add the value to the end of the list.
Consider the following example in which, we are taking the elements of the list from the user and printing the list on the console.
l =[];  
n = int(input("Enter the number of elements in the list")); #Number of elements will be entered by the user  
for i in range(0,n): # for loop to take the input  
    l.append(input("Enter the item?")); # The input is taken from the user and added to the list as the item  
print("printing the list items....");   
for i in l: # traversal loop to print the list items  
    print(i, end = "  ");   
>>>Output:
Enter the number of elements in the list 5
Enter the item?1
Enter the item?2
Enter the item?3
Enter the item?4
Enter the item?5
printing the list items....
1  2  3  4  5 

Removing elements from the list
List = [0,1,2,3,4]   
print("printing original list: ");  
for i in List:  
    print(i,end=" ")  
List.remove(0)  
print("\nprinting the list after the removal of first element...")  
for i in List:  
    print(i,end=" ")  
>>>Output:
printing original list: 
0 1 2 3 4 
printing the list after the removal of first element...

1 2 3 4 

Python List Built-in functions
Python provides the following built-in functions which can be used with the lists.
SN
Function
Description
1
cmp(list1, list2)
It compares the elements of both the lists.
2
len(list)
It is used to calculate the length of the list.
3
max(list)
It returns the maximum element of the list.
4
min(list)
It returns the minimum element of the list.
5
list(seq)
It converts any sequence to the list.
Python List built-in methods

Function
Description
list.append(obj)
The element represented by the object obj is added to the list.
2  
list.clear()
It removes all the elements from the list.
3  
List.copy()
It returns a shallow copy of the list.
4  
list.count(obj)
It returns the number of occurrences of the specified object in the list.
5  
list.extend(seq)
The sequence represented by the object seq is extended to the list.
6  
list.index(obj)
It returns the lowest index in the list that object appears.
7  
list.insert(index, obj)
The object is inserted into the list at the specified index.
8  
list.pop(obj=list[-1])
It removes and returns the last object of the list.
9  
list.remove(obj)
   It removes the specified object from the list.
10 
list.reverse()
   It reverses the list.
11 
list.sort([func])
   It sorts the list by using the specified compare function if given.

Tuple
A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.
Creating Tuples
# An empty tuple
empty_tuple = ()
print (empty_tuple)
Output: ()
# Creating non-empty tuples
# One way of creation
tup = 'python', 'geeks'
print(tup)
# Another for doing the same
tup = ('python', 'geeks')
print(tup)
Output
('python', 'geeks')
('python', 'geeks')
Note: In case your generating a tuple with a single element, make sure to add a comma after the element.

Concatenation of Tuples
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
# Concatenating above two
print(tuple1 + tuple2)
Output:(0, 1, 2, 3, ‘python’, ‘geek’)

Nesting of Tuples
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
Output :((0, 1, 2, 3), ‘python’, ‘geek’)

Repetition in Tuples
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
Output :(‘python’,’python’,’python’,)
Try the above without a comma and check. You will get tuple3 as a string 'pythonpythonpython’.

Slicing in Tuples
# code to test slicing
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
Output
(1,2,3)
(3,2,1,0)
(2,3)

Deleting a Tuple
# Code for deleting a tuple
tuple3 = ( 0, 1)
del tuple3
print(tuple3)
Error:
Traceback (most recent call last):
  File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
    print(tuple3)
NameError: name 'tuple3' is not defined
Output:
(0, 1)

Finding Length of a Tuple
# Code for printing the length of a tuple
tuple2 = ('python', 'geek')
print(len(tuple2))
Output : 2
Converting list to a Tuple
# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python'
Output : (0,1,2)
(‘p’,’y’,’t’,’h’,’o’,’n’)
Takes a single parameter which may be a list,string,set or even a dictionary( only keys are taken as elements) and converts them to a tuple.
Tuples in a loop
#python code for creating tuples in a loop
tup = ('geek',)
n = 5  #Number of time loop runs
for i in range(int(n)):
    tup = (tup,)
    print(tup)
Output : 
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),) 

Using cmp(), max() , min()
# A python program to demonstrate the use of 
# cmp(), max(), min()
tuple1 = ('python', 'geek')
tuple2 = ('coder', 1)
if (cmp(tuple1, tuple2) != 0):
    # cmp() returns 0 if matched, 1 when not tuple1 
    # is longer and -1 when tuple1 is shoter
    print('Not the same')
else:
    print('Same')
print ('Maximum element in tuples 1,2: ' + 
        str(max(tuple1)) +  ',' + 
        str(max(tuple2)))
print ('Minimum element in tuples 1,2: ' + 
     str(min(tuple1)) + ','  + str(min(tuple2)))
Output:
Not the same
Maximum element in tuples 1,2: python,coder
Minimum element in tuples 1,2: geek,1
Note: max() and min() checks the based on ASCII values. If there are two strings in a tuple, then the first different character in the strings are checked.

Dictionary
Dictionary is used to implement the key-value pair in python. The dictionary is the data type in python which can simulate the real-life data arrangement where some specific value exists for some particular key.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any python object whereas the keys are the immutable python object, i.e., Numbers, string or tuple.
Dictionary simulates Java hash-map in python.

Creating the dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the small brackets () and separated by the colon (:). The collections of the key-value pairs are enclosed within the curly braces {}.
The syntax to define the dictionary is given below.
Dict = {"Name": "Ayush","Age": 22}  
In the above dictionary Dict, The keys Name, and Age are the string that is an immutable object.
Let's see an example to create a dictionary and printing its content.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
print(type(Employee))  
print("printing Employee data .... ")  
print(Employee)  
>>>Output
<class 'dict'>
printing Employee data .... 
{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}
Accessing the dictionary values
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary.
The dictionary values can be accessed in the following way.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
print(type(Employee))  
print("printing Employee data .... ")  
print("Name : %s" %Employee["Name"])  
print("Age : %d" %Employee["Age"])  
print("Salary : %d" %Employee["salary"])  
print("Company : %s" %Employee["Company"])  
>>>Output:
<class 'dict'>
printing Employee data .... 
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing.

Updating dictionary values
The dictionary is a mutable data type, and its values can be updated by using the specific keys.
Let's see an example to update the dictionary values.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
print(type(Employee))  
print("printing Employee data .... ")  
print(Employee)  
print("Enter the details of the new employee....");  
Employee["Name"] = input("Name: ");  
Employee["Age"] = int(input("Age: "));  
Employee["salary"] = int(input("Salary: "));  
Employee["Company"] = input("Company:");  
print("printing the new data");  
print(Employee)  
>>>Output:
<class 'dict'>
printing Employee data .... 
{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}
Enter the details of the new employee....
Name: David
Age: 19
Salary: 8900
Company:JTP
printing the new data
{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}

Deleting elements using del keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
print(type(Employee))  
print("printing Employee data .... ")  
print(Employee)  
print("Deleting some of the employee data")   
del Employee["Name"]  
del Employee["Company"]  
print("printing the modified information ")  
print(Employee)  
print("Deleting the dictionary: Employee");  
del Employee  
print("Lets try to print it again ");  
print(Employee)  
>>>Output:
<class 'dict'>
printing Employee data .... 
{'Age': 29, 'Company': 'GOOGLE', 'Name': 'John', 'salary': 25000}
Deleting some of the employee data
printing the modified information 
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again 
Traceback (most recent call last):
  File "list.py", line 13, in <module>
    print(Employee)
NameError: name 'Employee' is not defined

Iterating Dictionary
A dictionary can be iterated using the for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee:  
    print(x);  
>>>Output:
Name
Company
salary
Age
Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee:  
    print(Employee[x]);  
>>>Output:
29
GOOGLE
John
25000
Example 3
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee.values():  
    print(x);  
>>>Output:
GOOGLE
25000
John
29
Example 4
#for loop to print the items of the dictionary by using items() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  
for x in Employee.items():  
    print(x);  
>>>Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Properties of Dictionary keys
1. In the dictionary, we can not store multiple values for the same keys. If we pass more than one values for a single key, then the value which is last assigned is considered as the value of the key.
Consider the following example.
Employee = {"Name": "John", "Age": 29, "Salary":25000,"Company":"GOOGLE","Name":"Johnn"}  
for x,y in Employee.items():  
    print(x,y)  
>>>Output:
Salary 25000
Company GOOGLE
Name Johnn
Age 29
2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuple as the key but we can not use any mutable object like the list as the key in the dictionary.
Consider the following example.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}  
for x,y in Employee.items():  
    print(x,y)  
>>>Output:
Traceback (most recent call last):
  File "list.py", line 1, in 
    Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

Built-in Dictionary functions
The built-in python dictionary methods along with the description are given below.
SN
Function
Description
1
cmp(dict1, dict2)
It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false.
2
len(dict)
It is used to calculate the length of the dictionary.
3
str(dict)
It converts the dictionary into the printable string representation.
4
type(variable)
It is used to print the type of the passed variable.


Built-in Dictionary methods
The built-in python dictionary methods along with the description are given below.
SN
Method
Description
1
dic.clear()
It is used to delete all the items of the dictionary.
2
dict.copy()
It returns a shallow copy of the dictionary.
3
dict.fromkeys(iterable, value = None, /)
Create a new dictionary from the iterable with the values equal to value.
4
dict.get(key, default = "None")
It is used to get the value specified for the passed key.
5
dict.has_key(key)
It returns true if the dictionary contains the specified key.
6
dict.items()
It returns all the key-value pairs as a tuple.
7
dict.keys()
It returns all the keys of the dictionary.
8
dict.setdefault(key,default= "None")
It is used to set the key to the default value if the key is not specified in the dictionary
9
dict.update(dict2)
It updates the dictionary by adding the key-value pair of dict2 to this dictionary.
10
dict.values()
It returns all the values of the dictionary.
11
len()
12
popItem()
13
pop()
14
count()
15
index()

Python Set

The set in python can be defined as the unordered collection of various items enclosed within the curly braces. The elements of the set can not be duplicate. The elements of the python set must be immutable.

Creating a set
The set can be created by enclosing the comma separated items with the curly braces. Python also provides the set method which can be used to create the set by the passed sequence.
Example 1: using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}  
print(Days)  
print(type(Days))  
print("looping through the set elements ... ")  
for i in Days:  
    print(i)  
>>>Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ... 
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Difference between discard() and remove()
Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove().
If the key to be deleted from the set using discard() doesn't exist in the set, the python will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the python will give the error.
Consider the following example.

Example
Months = set(["January","February", "March", "April", "May", "June"])  
print("\nprinting the original set ... ")  
print(Months)  
print("\nRemoving items through discard() method...");  
Months.discard("Feb"); #will not give an error although the key feb is not available in the set  
print("\nprinting the modified set...")  
print(Months)  
print("\nRemoving items through remove() method...");  
Months.remove("Jan") #will give an error as the key jan is not available in the set.   
print("\nPrinting the modified set...")  
print(Months)  
Output:

printing the original set ... 
{'March', 'January', 'April', 'June', 'February', 'May'}
Removing items through discard() method...
printing the modified set...
{'March', 'January', 'April', 'June', 'February', 'May'}
eRemoving items through remove() method...
Traceback (most recent call last):
  File "set.py", line 9, in 
    Months.remove("Jan")
KeyError: 'Jan'

No comments:

Post a Comment

Python Datatype Interview Questions

Q)  What is Python? Python is a high-level, interpreted, interactive, and object-oriented scripting language. Python is designed to be...