
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialProgramming
4.5 Rating 100 Questions 30 mins read8 Readers

There are a couple of ways to check if a file exists or not. First method is use open() function on a file and see if it raises any exception. If the file is indeed existing, the open() function will be executed correctly. However, if it doesn’t, an exception will be raised.
>>> try:
file=open(filename)
print ('the file exists')
file.close()
except:
print ('file is not existing')You can also use exists() method of path object defined in os module.
>>> from os import path >>> path.exists(filename)
Here filename should be a string containing name along with file’s path. Result will be True if file exists otherwise false.
Python library consists of pathlib module. You can also check if file exists or not by using exists() method in this module as follows:
>>> import pathlib >>> file=pathlib.Path(filename) >>> file.exists()
Computer languages are generally classified as statically or dynamically typed. Examples of statically typed languages are C/C++, Java, C# etc. Python, along with JavaScript, PHP etc are dynamically typed languages.
First we have to understand the concept of variable. In C/C++/Java, variable is a user defined convenience name given to a memory location. Moreover, compilers of these languages require prior declaration of name of variable and type of data that can be stored in it before actually assigning any value. Typical variable declaration and assignment statement in C/C++/Java would be as follows:
int x; x=10;
Here, the variable x is permanently bound to int type. If data of any other type is assigned, compiler error will be reported. Type of variable decides what can be assigned to it and what can’t be assigned.
In Python on the other hand, the object is stored in a randomly chosen memory location, whereas variable is just an identifier or a label referring to it. When we assign 10 to x in Python, integer object 10 is stored in memory and is labelled as x. Python’s built-in type() function tells us that it stores object of int type.
>>> x=10 >>> type(x) <class 'int'>
However, we can use same variable x as a label to another object, which may not be of same type.
>>> x='Hello' >>> type(x) <class 'str'>
Python interpreter won’t object if same variable is used to store reference to object of another type. Unlike statically typed languages, type of variable changes dynamically as per the object whose reference has been assigned to it. Python is a dynamically typed language because type of variable depends upon type of object it is referring to.
Depending upon how strict its typing rules are, a programming language is classified as strongly typed or weakly (sometimes called loosely) typed.
Strongly typed language checks the type of a variable before performing an operation on it. If an operation involves incompatible types, compiler/interpreter rejects the operation. In such case, types must be made compatible by using appropriate casting techniques.
A weakly typed language does not enforce type safety strictly. If an operation involves two incompatible types, one of them is coerced into other type by performing implicit casts. PHP and JavaScript are the examples of weakly typed languages.
Python is a strongly typed language because it raises TypeError if two incompatible types are involved in an operation
>>> x=10 >>> y='Python' >>> z=x+y Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> z=x+y TypeError: unsupported operand type(s) for +: 'int' and 'str'
In above example, attempt to perform addition operation on one integer object and another string object raises TypeError as neither is implicitly converted to other. If however, the integer object “I” converted to string then concatenation is possible.
>>> x=10 >>> y='Python' >>> z=str(x)+y >>> z '10Python'
In a weakly typed language such as JavaScript, the casting is performed implicitly.
<script> var x = 10; var y = "Python"; var z=x+y; document.write(z); </script> Output: 10Python
Literal representation of Python string can be done using single, double or triple quotes. Following are the different ways in which a string object can be declared:
>>> s1='Hello Python' >>> s2="Hello Python" >>> s3='''Hello Python''' >>> s4="""Hello Python"""
However, if a string contains any of the escape sequence characters, they are embedded inside the quotation marks. The back-slash character followed by certain alphabets carry a special meaning. Some of the escape characters are:
>>> s1='Hello\nPython' >>> sprint (s1) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> sprint (s1) NameError: name 'sprint' is not defined >>> print (s1) Hello Python >>> s2='Hello\tPython' >>> print (s2) Hello Python
In case of a raw string on the other hand the escape characters don’t get translated while printing. Such raw string is prepared by prefixing ‘r’ or ‘R’ to the leading quotation mark(single, double or triple)
>>> r1=r'Hello\nPython' >>> print (r1) Hello\nPython >>> r2=R"Hello\tPython" >>> print (r2) Hello\tPython
Python doesn’t allow any undefined escape sequence to be embedded in the quotation marks of a normal string.
>>> s1='Hello\xPython' SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 5-6: truncated \xXX escape
However, in a raw string, any character followed by backslash may be used because anyway it is not going to be interpreted for its meaning!
>>> s1=r'Hello\xPython' >>> print (s1) Hello\xPython
Raw strings are used in building regular expressions (called regex). Python’s re module provides functions to process the regular expressions. The re module assigns its own escape characters. Some of them are listed below:
| \d | Matches any decimal digit |
| \D | Matches any non-digit character |
| \s | Matches any whitespace character |
| \S | Matches any non-whitespace character |
| \w | Matches any alphanumeric character |
| \W | Matches any non-alphanumeric character. |
| \b | boundary between word and non-word and /B is opposite of /b |
Some examples of above escape characters are given below:
>>> import re
>>> string='ab12cd34ef'
>>> #find all digits
>>> x = re.findall("\d", string)
>>> print (x)
['1', '2', '3', '4']
>>> #find all non-digit characters
>>> x = re.findall("\D", string)
>>> print (x)
['a', 'b', 'c', 'd', 'e', 'f']Built-in pow() function has two variations - with two arguments and three arguments.
The pow() function with two arguments returns first argument raised to second argument. That means pow(x,y) results in x to the power y
>>> pow(10,2) 100
The two-argument form pow(x, y) is equivalent to using the power operator: x**y.
The pow() function can take three arguments. In that case, pow(x,y,z) returns pow(x,y)%z. It returns modulo division of x to the power y and z.
>>> pow(10,2) 100 >>> pow(10,2,3) 1
This is equivalent to10**2%3 which is 100%3 = 1
The pow() function from math module only has a two argument version. Both the arguments are treated as float. Hence the result is always float even if arguments are int.
>>> math.pow(10,2) 100.0 >>> pow(10,2) 100
Because of the floating point representation in the memory, result of math.pow() may be inaccurate for integer arguments. Hence for integers it is advised to use built-in pow() function or ** operator.
The built-in next() function calls __next__() method of iterator object to retrieve next item in it. So the next question would be – what is an iterator?
An object representing stream of data is an iterator. One element from the stream is retrieved at a time. It follows iterator protocol which requires it to support __iter__() and __next__() methods. Python’s built-in method iter() implements __iter__() method and next() implements __next__() method. It receives an iterable and returns iterator object.
Python uses iterators implicitly while working with collection data types such as list, tuple or string. That's why these data types are called iterables. We normally use ‘for’ loop to iterate through an iterable as follows:
>>> numbers=[10,20,30,40,50] >>> for num in numbers: print (num) 10 20 30 40 50
We can use iter() function to obtain iterator object underlying any iterable.
>>> iter('Hello World')
<str_iterator object at 0x7f8c11ae2eb8>
>>> iter([1,2,3,4])
<list_iterator object at 0x7f8c11ae2208>
>>> iter((1,2,3,4))
<tuple_iterator object at 0x7f8c11ae2cc0>
>>> iter({1:11,2:22,3:33})
<dict_keyiterator object at 0x7f8c157b9ea8>Iterator object has __next__() method. Every time it is called, it returns next element in iterator stream. When the stream gets exhausted, StopIteration error is raised.
>>> numbers=[10,20,30,40,50] >>> it=iter(numbers) >>> it.__next__() 10 >>> next(it) 20 >>> it.__next__() 30 >>> it.__next__() 40 >>> next(it) 50 >>> it.__next__() Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> it.__next__() StopIteration
Remember that next() function implements __next__() method. Hence next(it) is equivalent to it.__next__()
When we use a for/while loop with any iterable, it actually implements iterator protocol as follows:
>>> while True: try: num=it.__next__() print (num) except StopIteration: break 10 20 30 40 50
A disk file, memory buffer or network stream also acts as an iterator object. Following example shows that each line from a file can be printed using next() function.
>>> file=open('csvexample.py')
>>> while True:
tr
KeyboardInterrupt
>>> while True:
try:
line=file.__next__()
print (line)
except StopIteration:
breakThis is one of the most frequently asked Python interview questions for freshers in recent times. Make sure you get this one correct.
List comprehension technique is similar to mathematical set builder notation. A classical for/while loop is generally used to traverse and process each item in an iterable. List comprehension is considerably more efficient than processing a list by ‘for’ loop. It is a very concise mechanism of creating new list by performing a certain process on each item of existing list.
Suppose we want to compute square of each number in a list and store squares in another list object. We can do it by a ‘for’ loop as shown below:
squares=[] for num in range(6): squares.append(pow(num,2)) print (squares)
The squares list object is displayed as follows:
[0, 1, 4, 9, 16, 25]
Same result is achieved by list comprehension technique much more efficiently. List comprehension statement uses following syntax:
newlist = [x for x in sequence]
We use above format to construct list of squares using list comprehension.
>>> numbers=[6,12,8,5,10] >>> squares = [x**2 for x in numbers] >>> squares [36, 144, 64, 25, 100]
We can even generate a dictionary or tuple object as a result of list comprehension.
>>> [{x:x*10} for x in range(1,6)]
[{1: 10}, {2: 20}, {3: 30}, {4: 40}, {5: 50}]Nested loops can also be used in a list comprehension expression. To obtain list of all combinations of items from two lists (Cartesian product):
>>> [{x:y} for x in range(1,3) for y in (11,22,33)]
[{1: 11}, {1: 22}, {1: 33}, {2: 11}, {2: 22}, {2: 33}]The resulting list stores all combinations of one number from each list
We can even have if condition in list comprehension. Following statement will result in list of all non-vowel alphabets in a string.
>>> odd=[x for x in range(1,11) if x%2==1] >>> odd [1, 3, 5, 7, 9]
Python’s yield keyword is typically used along with a generator. A generator is a special type of function that returns an iterator object returning stream of values. Apparently it looks like a normal function , but it doesn’t return a single value. Just as we use return keyword in a function, in a generator yield statement is used.
A normal function, when called, executes all statements in it and returns back to calling environment. The generator is called just like a normal function. However, it pauses on encountering yield keyword, returning the yielded value to calling environment. Because execution of generator is paused, its local variables and their states are saved internally. It resumes when __next__() method of iterator is called. The function finally terminates when __next__() or next() raises StopIteration.
In following example function mygenerator() acts as a generator. It yields one character at a time from the string sequence successively on every call of next()
>>> def mygenerator(string):
for ch in string:
print ("yielding", ch)
yield chThe generator is called which builds the iterator object
>>> it=mygenerator("Hello World")Each character from string is pushed in iterator every time next() function is called.
>>> while True:
try:
print ("yielded character", next(it))
except StopIteration:
print ("end of iterator")
breakOutput:
yielding H yielded character H yielding e yielded character e yielding l yielded character l yielding l yielded character l yielding o yielded character o yielding yielded character yielding W yielded character W yielding o yielded character o yielding r yielded character r yielding l yielded character l yielding d yielded character d end of iterator
In case of generator, elements are generated dynamically. Since next item is generated only after first is consumed, it is more memory efficient than iterator.
Each Python object, whether representing a built-in class or a user defined class, is stored in computer’s memory at a certain randomly chosen location which is returned by the built-in id() function.
>>> x=10 >>> id(x) 94368638893568
Remember that variable in Python is just a label bound to the object. Here x represents the integer object 10 which is stored at a certain location.
Further, if we assign x to another variable y, it is also referring to the same integer object.
>>> y=x >>> id(y) 94368638893568
Let us now change value of x with expression x=x+1. As a result a new integer 11 is stored in memory and that is now referred to by x. The object 10 continues to be in memory which is bound to y.
>>> x=x+1 >>> id(x) 94368638893600 >>> id(y) 94368638893568
Most striking feature is that the object 10 is not changed to 11. A new object 11 is created. Any Python object whose value cannot be changed after its creation is immutable. All number type objects (int, float, complex, bool, complex) are immutable.
String object is also immutable. If we try to modify the string by replacing one of its characters, Python interpreter doesn’t allow this, raising TypeError thus implying that a string object is immutable.
>>> string='Python' >>> string[2]='T' Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> string[2]='T' TypeError: 'str' object does not support item assignment
Same thing is true with tuple which is also immutable.
>>> tup=(10,20,30) >>> tup[1]=100 Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> tup[1]=100 TypeError: 'tuple' object does not support item assignment
However, list and dictionary objects are mutable. These objects can be updated in place.
>>> num=[10,20,30]
>>> num[1]=100
>>> num
[10, 100, 30]
>>> dct={'x':10, 'y':20, 'z':30}
>>> dct['y']=100
>>> dct
{'x': 10, 'y': 100, 'z': 30}Set is a collection data type in Python. It is a collection of unique and immutable objects, not necessarily of same types. A set object can be created by a literal representation as well as using built-in set() function.
Comma separated collection of items enclosed in curly brackets is a set object.
>>> s={10,'Hello', 2.52}
>>> type(s)
<class 'set'>You can also use built-in set() function which in fact is constructor of set class. It constructs a set object from an iterable argument such as list, tuple or string.
>>> s1=set([10,20,30])
>>> s1
{10, 20, 30}
>>> s2=set((100,200,300))
>>> s2
{200, 100, 300}
>>> s3=set('Hello')
>>> s3
{'o', 'e', 'l', 'H'}Items in the iterable argument may not appear in the same order in set collection. Also, set is a collection of unique objects. Therefore, even if the iterable contains repeated occurrence of an item, it will appear only one in set. You can see just one presence of ‘l’ even if it appears twice in the string.
Items in the set collection must be mutable. It means a list or a dict object cannot be one of the items in a set although tuple is allowed.
>>> s={1,(2,3)}
>>> s
{1, (2, 3)}
>>> s={1,[2,3]}
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
s={1,[2,3]}
TypeError: unhashable type: 'list'Even though set can contain only immutable objects such as number, string or tuple, set itself is mutable. It is possible to perform add/remove/clear operations on set.
>>> s1=set([10,20,30])
>>> s1.add(40)
>>> s1
{40, 10, 20, 30}
>>> s1.remove(10)
>>> s1
{40, 20, 30}Frozenset object on the other hand is immutable. All other characteristics of frozenset are similar to normal set. Because it is immutable add/remove operations are not possible.
>>> f=frozenset([10,20,30])
>>> f
frozenset({10, 20, 30})
>>> f.add(40)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
f.add(40)
AttributeError: 'frozenset' object has no attribute 'add'Python’s set data type is implementation of set as in set theory of Mathemetics. Operations such as union, intersection, difference etc. can be done on set as well as frozenset.
Any class in Python code, whether built-in or user defined, is an object of ‘type’ class which is called a 'metaclass'. A metaclass is a class whose objects are also classes. This relationship can be understood by the following diagram:

Python library's built-in function type() returns class to which an object belongs.
>>> num=50 >>> type(num) <class 'int'> >>> numbers=[11.,22,33] >>> type(numbers) <class 'list'> >>> lang='Python' >>> type(lang) <class 'str'>
Same thing applies to object of a user defined class
>>> class user: def __init__self(): self.name='xyz' self.age=21 >>> a=user() >>> type(a) <class '__main__.user'>
Interestingly, class is also an object in Python. Each class, both built-in class and a user defined class is an object of type class
>>> type(int) <class 'type'> >>> type(list) <class 'type'> >>> type(str) <class 'type'> >>> type(user) <class 'type'>
Can be rephrased and mentioned at the start along with the diagram and the tables above can be used as an example instead.
The type class is the default metaclass. The type() function used above takes an object as argument. The type() function's three argument variation is used to define a class dynamically. Its prototype is as follows:
newclass=type(name, bases, dict)
The function returns class that has been created dynamically. Three arguments of type function are:
| name | name of the class which becomes __name__ attribute of new class |
| bases | tuple consisting of parent classes. Can be blank if not a derived class |
| dict | dictionary forming namespace of the new class containing attributes and methods and their values. |
Following statement creates user dynamically using type() function:
>>> user=type('user',(), {'name':'xyz', 'age':21})We can now use this class in the same manner as we do when it is defined using class statement:
>>> a=user()
>>> a.name,a.age
('xyz', 21)
>>> type(a)
<class '__main__.user'>Similarly you can add instance method dynamically.
>>> def userdata(self):
print('name:{}, age:{}'.format(self.name, self.age))
>>> user=type('user',(), {'name':'xyz', 'age':21,'userdata':userdata})
>>> a=user()
>>> a.userdata()
name:xyz, age:21Moreover, this class can be used to create an inherited class as well.
>>> newuser=type('newuser',(user,),{})
>>> b=newuser()
>>> b.userdata()
name:xyz, age:21As mentioned above, type is the default metaclass. A class that it inherited from type is a custom metaclass.
>>> class NewMetaClass(type): pass
Using this custom metaclass to create new class as follows:
>>> class newclass(metaclass=NewMetaClass): pass
Newly created class can even be used as base for other.
>>> class subclass(newclass): pass
The custom metaclass is a type of both the classes.
>>> type(NewMetaClass) <class 'type'> >>> type(newclass) <class '__main__.NewMetaClass'> >>> type(subclass) <class '__main__.NewMetaClass'>
Construction of subclass of user defined metaclass can be customized by overriding __new__ magic method.
In following example, we declare a metaclass (NewMetaClass) having __new__() method. It returns instance of new class which in turn is initialized by __init__() method as usual in the derived class.
lass NewMetaClass(type):
def __new__(cls, name, bases, dict):
print ('name:',name)
print ('bases:',bases)
print ('dict:',dict)
inst = super().__new__(cls, name, bases, dict)
return inst
class myclass(metaclass=NewMetaClass):
pass
class newclass(myclass,metaclass=NewMetaClass):
def __init__(self):
self.name='xyz'
self.age=21When we declare an object of newclass and print its attributes, following output is displayed.
x=newclass()
print('name:',x.name, 'age:',x.age)
print ('type:',type(x))Output:
name: myclass
bases: ()
dict: {'__module__': '__main__', '__qualname__': 'myclass'}
name: newclass
bases: (<class '__main__.myclass'>,)
dict: {'__module__': '__main__', '__qualname__': 'newclass', '__init__': <function newclass.__init__ at 0x7f65d8dfcf28>}
name: xyz age: 21
type: <class '__main__.newclass'>We can thus customize the metaclass and creation of its subclasses.
Array is a collection of more than one element of similar data type in C/C++/Java etc. Python doesn't have any built-in equivalent of array. Its List/tuple data types are collections, but items in it may be of different types.
Python's array module emulates C type array. The module defines 'array' class whose constructor requires two arguments:
array(typecode, initializer)
The typecode determines the type of array. Initializer should be a sequence with all elements of matching type.
| Type code | C Type | Python Type |
|---|---|---|
| 'b' | signed char | int |
| 'B' | unsigned char | int |
| 'u' | Py_UNICODE | Unicode character |
| 'h' | signed short | int |
| 'H' | unsigned short | int |
| 'i' | signed int | int |
| 'I' | unsigned int | int |
| 'I' | signed long | int |
| 'L' | unsigned long | int |
| 'q' | signed long long | int |
| 'Q' | unsigned long long | int |
| 'f' | Float | float |
| 'd' | Double | float |
The array module defines typecodes attribute which returns a string. Each character in the string represents a type code.
>>> array.typecodes 'bBuhHiIlLqQfd'
Following statement creates an integer array object:
>>> import array
>>> arr=array.array('i', range(5))
>>> arr
array('i', [0, 1, 2, 3, 4])
>>> type(arr)
<class 'array.array'>The initializer may be a byte like object. Following example builds an array from byte representation of string.
>>> arr=array.array('b', b'Hello')
>>> arr
array('b', [72, 101, 108, 108, 111])Some of the useful methods of the array class are as follows:
extend():
This method appends items from list/tuple to the end of the array. Data type of array and iterable list/tuple must match; if not, TypeError will be raised.
>>> arr=array.array('i', [0, 1, 2, 3, 4])
>>> arr1=array.array('i',[10,20,30])
>>> arr.extend(arr1)
>>> arr
array('i', [0, 1, 2, 3, 4, 10, 20, 30])fromfile():
This method reads data from the file object and appends to an array.
>>> a=array.array('i')
>>> file=open('test.txt','rb')
>>> a.fromfile(file,file.tell())
>>> a
array('i', [1819043144, 2035294319, 1852794996])tofile():
This method write all items to the file object which must have write mode enabled.
>>> a=array.array('i', [10, 20, 30, 40, 50])
>>> file=open("temp.txt","wb")
>>> a.tofile(file)
>>> file.close()
>>> file=open("temp.txt","rb")
>>> file.read()
b'\n\x00\x00\x00\x14\x00\x00\x00\x1e\x00\x00\x00(\x00\x00\x002\x00\x00\x00'append():
This method appends a new item to the end of the array
fromlist():
This method appends items from the list to array. This is equivalent to for x in list: a.append(x)
>>> a=array.array('i')
>>> a.append(10)
>>> a
array('i', [10])
>>> num=[20,30,40,50]
>>> a.fromlist(num)
>>> a
array('i', [10, 20, 30, 40, 50])insert():
Insert a new item in the array before specified position
>>> a=array.array('i', [10, 20, 30, 40, 50])
>>> a.insert(2,25)
>>> a
array('i', [10, 20, 25, 30, 40, 50])pop():
This method returns item at given index after removing it from the array.
>>> a=array.array('i', [10, 20, 30, 40, 50])
>>> x=a.pop(2)
>>> x
30
>>> a
array('i', [10, 20, 40, 50])remove():
This method removes first occurrence of given item from the array.
>>> a=array.array('i', [10, 20, 30, 40, 50])
>>> a.remove(30)
>>> a
array('i', [10, 20, 40, 50])In programming language context, a first-class object is an entity that can perform all the operations generally available to other scalar data types such as integer, float or string.
As they say, everything in Python is an object and this applies to function (or method) as well.
>>> def testfunction():
print ("hello")
>>> type(testfunction)
<class 'function'>
>>> type(len)
<class 'builtin_function_or_method'>As you can see, a built-in function as well as user defined function is an object of function class.
Just as you can have built-in data type object as argument to a function, you can also declare a function with one of its arguments being a function itself. Following example illustrates it.
>>> def add(x,y): return x+y >>> def calladd(add, x,y): z=add(x,y) return z >>> calladd(add,5,6) 11
Return value of a function can itself be another function. In following example, two functions add() and multiply() are defined. Third function addormultiply() returns one of the first two depending on arguments passed to it.
>>> def add(x,y): return x+y >>> def multiply(x,y): return x*y >>> def addormultiply(x,y,op): if op=='+': return add(x,y) else: if op=='*': return multiply(x,y) >>> addormultiply(5,6,'+') 11 >>> addormultiply(5,6,'*') 30
Thus a function in Python is an object of function class and can be passed to other function as argument or a function can return other function. Hence Python function is a high order object.
This is one of the most frequently asked Python interview questions for Data Science in recent times. Practice this with other data types as well.
Python has a built-in file object that represents a disk file. The file API has write() and read() methods to store data in Python objects in computer files and read it back.
To save data in a computer file, file object is first obtained from built-in open() function.
>>> fo=open("file.txt","w")
>>> fo.write("Hello World")
11
>>> fo.close()Here ‘w’ as mode parameter of open() function indicates that file is opened for writing data. To read back the data from file open it with ‘r’ mode.
>>> fo=open("file.txt","r")
>>> fo.read()
'Hello World'However, the file object can store or retrieve only string data. For other type of objects, they must be either converted to string or their byte representations and store in binary files opened with ‘wb’ mode.
This type of manual conversion of objects in string or byte format (and vice versa) is very cumbersome. Answer to this situation is object serialization.
Object serialization means transforming it in a format that can be stored, so as to be able to deserialize it later, recreating the original object from the serialized format. Serialization may be done disk file, byte string or can be transmitted via network sockets. When serialized data is brought back in a form identical to original, the mechanism is called de-serialization.
Pythonic term for serialization is pickling while de-serialization is often referred to as unpickling. Python’ library contains pickle module that provides dumps() and loads() functions to serialize and deserialize Python objects.
Following code shows a dictionary object pickled using dumps() function in pickle module.
>>> import pickle
>>> data={'No':1, 'name':'Rahul', 'marks':50.00}
>>> pckled=pickle.dumps(data)
>>> pckled
b'\x80\x03}q\x00(X\x02\x00\x00\x00Noq\x01K\x01X\x04\x00\x00\x00nameq\x02X\x05\x00\x00\x00Rahulq\x03X\x05\x00\x00\x00marksq\x04G@I\x00\x00\x00\x00\x00\x00u.'Original state of object is retrieved from pickled representation using loads() function.
>>> data=pickle.loads(pckled)
>>> data
{'No': 1, 'name': 'Rahul', 'marks': 50.0}The serialized representation of data can be persistently stored in disk file and can be retried back using dump() and load() functions.
>>> import pickle
>>> data={'No':1, 'name':'Rahul', 'marks':50.00}
>>> fo=open('pickledata.txt','wb')
>>> pickle.dump(data, fo)
>>> fo.close()
>>> #unpickle
>>> fo=open('pickledata.txt','rb')
>>> data=pickle.load(fo)
>>> data
{'No': 1, 'name': 'Rahul', 'marks': 50.0}Pickle data format is Python-specific in nature. To serialize and deserialize data to/from other standard formats Python library provides json, csv and xml modules.
As we can see, serialized data can be persistently stored in files. However, file created using write() method of file object does store data persistently but is not in serialized form. Hence we can say that serialized data can be stored persistently, but converse is not necessarily true.
This module implements pseudo-random number generator (PRNG) technique that uses the Mersenne Twister algorithm. It produces 53-bit precision floats and has a period of 2**19937-1. The module functions depend on the basic function random(), which generates a random float uniformly in the range 0.0 to 1.0.
The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for cryptographic purposes.
Starting from Python 3.6, the secrets module has been added to Python standard library for generating cryptographically strong random numbers (CSPRNG) suitable for managing data such as passwords, account authentication, security tokens, etc.
It is recommended that, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.
Here’s how a secure password can be generated using secrets module. Let the password have one character each from group of uppercase characters, lowercase characters, digits and special characters.
Characters in these groups can be obtained by using following attributes defined in string module.
>>> import string >>> upper=string.ascii_uppercase >>> lower=string.ascii_lowercase >>> dig=string.digits >>> sp=string.punctuation
We now randomly choose one character from each group using choice() function.
>>> a=secrets.choice(upper) >>> a 'E' >>> b=secrets.choice(lower) >>> b 'z' >>> c=secrets.choice(dig) >>> c '2' >>> d=secrets.choice(sp) >>> d ':'
Finally these four characters are shuffled randomly and joined to produce a cryptographically secure password.
>>> pwd=[a,b,c,d] >>> secrets.SystemRandom().shuffle(pwd) >>> ''.join(pwd) ':Ez2'