SlideShare uma empresa Scribd logo
1 de 68
What is the difference between shallowcopy and deepcopy?
1
Child1
Child2
Child3
Object 1
Child1
Child2
Child3
Object 2
Deep copy creates a different object and populates it with
the child objects of the original object.
Therefore, changes in the original object is not reflected in
the copy
copy.deepcopy() creates a deep copy
Child1
Child2
Child3
Object 1 Object 2
Shallow copy creates a different object and populates it
with the references of the child objects within the original
object.
Therefore, changes in the original object is reflected in the
copy
copy.copy creates a shallow copy
How is multithreading achieved in Python?
2
Multithreading usually implies that multiple threads are executed
concurrently
The Python Global Interpreter Lock doesn’t allow more than one thread to
hold the Python interpreter at a particular point of time
So, multithreading in Python is achieved through context switching
Discuss the Django architecture
3
Model
Template
ViewURLDjangoUser
Template: The front end of the webpage
Model: The back end where the data is stored
View: Interacts with the Model and Template and Maps it to a URL
Django: Serves the page to the user
What advantage does Numpy array have over nested list?
4
• Numpy is written in C such that all its complexities are packed into a simple-to-use module
• Lists on the other hand are dynamically typed. Therefore, Python must check the data type of
each element every time it uses it
• This makes Numpy arrays much faster than lists
Lists Array
What is pickling and unpickling?
5
• Converting a byte stream to a Python object
hierarchy is called unpickling
• Unpickling is also referred to as deserialization
Pickling Unpickling
• Converting a Python object hierarchy to a byte
stream is called pickling
• Pickling is also referred to as serialization
How is memory managed in Python?
6
• Python has a private heap space where it stores all the objects
• The Python memory manager manages various aspects of this heap like sharing, caching,
segmentation and allocation
• The user has no control over the heap. Only the Python interpreter has this access
Private Heap
Garbage collector
Memory manager
Interpreter
Program
Are arguments in Python passed by value or by reference?
7
Arguments are passed in Python by reference. This means that any change
made within a function is reflected on the original object
def fun(l):
l[0]=3
l=[1,2,3,4]
fun(l)
print(l)
Output: [3,2,3,4]
def fun(l):
l=[3,2,3,4]
l=[1,2,3,4]
fun(l)
print(l)
Output: [1,2,3,4]
Lists are mutable
A new object is created
How would you generate random numbers in Python?
8
To generate random numbers in Python, you must first import the random module
> import random
How would you generate random numbers in Python?
8
To generate random numbers in Python, you must first import the random module
> import random
The random() function generates a random float value
between 0 and 1
> random.random()
How would you generate random numbers in Python?
8
To generate random numbers in Python, you must first import the random module
> import random
The random() function generates a random float value
between 0 and 1
> random.random()
The randrange() function generates a random number
within a given range
> random.randrange(1,10,2)
Syntax:
randrange(beginning, end, step)
What does the // operator do?
9
In Python, the / operator performs division and returns the quotient in float
For example:
5/2 returns 2.5
The // operator on the other hand, returns the quotient in integer
For example:
5//2 returns 2
What does the “is” operator do?
1
0
The “is” operator compares the id of the two objects
list1=[1,2,3] list2=[1,2,3] list3=list1
list1 == list2  True list1 is list2  False list1 is list3  True
What is the purpose of pass statement?
1
1
var="Si mplilea rn"
for i in var:
if i==" ":
pass
else:
print(i,end="")
No action is required
The pass statement is used when there’s a syntactic but not an operational
requirement
For example: The program below prints a string ignoring the spaces
How will you check if all characters in a string are alphanumeric?
1
2
• Python has an in built method
isalnum() which returns true if all
characters in the string are
alphanumeric
>> "abcd123".isalnum()
Output: True
>>”abcd@123#”.isalnum()
Output: False
How will you check if all characters in a string are alphanumeric?
1
2
• Python has an in built method
isalnum() which returns true if all
characters in the string are
alphanumeric
• One can also use regex instead
>>import re
>>bool(re.match(‘[A-Za-z0-9]+$','abcd123’))
Output: True
>> bool(re.match(‘[A-Za-z0-9]+$','abcd@123’))
Output: False
How will you merge elements in a sequence?
1
3
Sequence
There are three types of sequences in
Python:
• Lists
• Tuples
• Strings
How will you merge elements in a sequence?
1
3
Sequence
There are three types of sequences in
Python:
• Lists
• Tuples
• Strings
>>l1=[1,2,3]
>>l2=[4,5,6]
>>l1+l2
Output: [1,2,3,4,5,6]
How will you merge elements in a sequence?
1
3
Sequence
There are three types of sequences in
Python:
• Lists
• Tuples
• Strings
>>t1=(1,2,3)
>>t2=(4,5,6)
>>t1+t2
Output: (1,2,3,4,5,6)
How will you merge elements in a sequence?
1
3
Sequence
There are three types of sequences in
Python:
• Lists
• Tuples
• Strings
>>s1=“Simpli”
>>s2=“learn”
>>s1+s2
Output: ‘Simplilearn’
How will you remove all leading whitespaces in string?
1
4
Python provides the in built function lstrip(), to remove all leading spaces from a string
>>“ Python”.lstrip
Output: Python
How will you replace all occurrences of a substring with a new string?
1
5
The replace() function can be used with strings for replacing
a substring with a given string
>>"Hey John. How are you, john?".replace(“john",“John",1)
Output: “Hey John. How are you, john?”
Syntax:
str.replace(old, new, count)
replace() returns a new string without modifying the
original one
What is the difference between del and remove() on lists?
1
6
del
• del removes all elements of a
list within a given range
• Syntax: del list[start:end]
remove()
• remove() removes the first
occurrence of a particular
character
• Syntax: list.remove(element)
del
• del removes all elements of a
list within a given range
• Syntax: del list[start:end]
>>lis=[‘a’,’b’,’c’,’d
’]
>>del lis[1:3]
>>lis
Output: [“a”,”d”]
>>lis=[‘a’,’b’,’b’,’d
’]
>>lis.remove(‘b’)
>>lis
Output: [‘a’,’b’,’d’]
How to display the contents of text file in reverse order?
1
7
Open the file using the open() function
Store the contents of the file into a list
Reverse the contents of this list
Run a for loop to iterate through the list
Differentiate between append() and extend()
1
8
extend()append()
• Append() adds an element to the end of the list • extend() adds elements from an iterable to the
end of the list
>>lst=[1,2,3]
>>lst.append(4)
>>lst
Output:[1,2,3,4]
>>lst=[1,2,3]
>>lst.extend([4,5,6])
>>lst
Output:[1,2,3,4,5,6]
What’s the output of the below code? Justify your answer
1
9
>>def addToList(val, list=[]):
>> list.append(val)
>> return list
>>list1 = addToList(1)
>>list2 = addToList(123,[])
>>list3 = addToList('a’)
>>print ("list1 = %s" % list1)
>>print ("list2 = %s" % list2)
>>print ("list3 = %s" % list3)
list1 = [1,’a’]
list2 = [123]
lilst3 = [1,’a’]
Output
What’s the output of the below code? Justify your answer
1
9
>>def addToList(val, list=[]):
>> list.append(val)
>> return list
>>list1 = addToList(1)
>>list2 = addToList(123,[])
>>list3 = addToList('a’)
>>print ("list1 = %s" % list1)
>>print ("list2 = %s" % list2)
>>print ("list3 = %s" % list3)
list1 = [1,’a’]
list2 = [123]
lilst3 = [1,’a’]
Output
Default list is created only once
during function creation and not
during its call
What is the difference between a list and a tuple?20
Lists are mutable while tuples are immutable
>>lst = [1,2,3]
>>lst[2] = 4
>>lst
Output:[1,2,4]
>>tpl = (1,2,3)
>>tpl[2] = 4
>>tpl
Output:TypeError: 'tuple'
object does not support item
assignment
List Tuple
What is docstring in python?21
Docstrings are used in providing documentation
to various Python modules classes, functions
and methods
def add(a,b):
"""This function adds two numbers."""
sum=a+b
return sum
sum=add(10,20)
print("Accessing doctstring method 1:",add.__doc__)
print("Accessing doctstring method 2:",end="")
help(add)
This is a docstring
What is docstring in python?21
Docstrings are used in providing documentation
to various Python modules classes, functions
and methods
def add(a,b):
"""This function adds two numbers."""
sum=a+b
return sum
sum=add(10,20)
print("Accessing doctstring method 1:",add.__doc__)
print("Accessing doctstring method 2:",end="")
help(add)
This is a docstring
Accessing doctstring method 1: This function adds two numbers.
Accessing doctstring method 2: Help on function add in module __main__:
add(a, b)
This function adds two numbers.
Output:
How do you use print() without the newline?22
The solution to this is dependent on the Python version you are using
>>print(“Hi.”),
>>print(“How are you?”)
Output: Hi. How are you?
>>print(“Hi”,end=“ ”)
>>print(“How are you?”)
Output: Hi. How are you?
Python 2 Python 3
How do you use the split() function in Python?23
The split() function splits a string into a number of strings based on a specified
delimiter
string.split(delimiter,max)
The character based on which the
string is split. By default it’s space
The maximum number of splits
The maximum number of splits
How do you use the split() function in Python?23
The split() function splits a string into a number of strings based on a specified
delimiter
string.split(delimiter,max)
The character based on which the
string is split. Default is space
>>var=“Red,Blue,Green,Orange”
>>lst=var.split(“,”,2)
>>print(lst)
Output:
[‘Red’,’Blue’,’Green,Orange’]
Is Python object oriented or functional programming?24
Python follows Object Oriented Paradigm
• Python allows the creation of objects
and its manipulation through specific
methods
• It supports most of the features of
OOPs such as inheritance an
polymorphism
Python follows Functional Programming paradigm
• Functions may be used as first class
object
• Python supports Lambda functions
which are characteristic of functional
paradigm
Write a function prototype that takes variable number of arguments25
>>def fun(*var):
>> for i in var:
>> print(i)
>>fun(1)
>>fun(1,25,6)
def function_name(*list)
What is *args and **kwargs?26
*args **kwargs
Used in function prototype to accept
varying number of arguments
It’s an iterable object
def fun(*args)
Used in function prototype to accept varying
number of keyworded arguments
It’s an iterable object
def fun(**kwargs):
......
fun( colour=“red”,units=2)
"In Python, functions are first class objects" What do you understand from this?27
A function can be treated just like
an object
You can assign them to variablesYou can pass them as arguments
to other functions
You can return them from other
functions
What is the output of : print(__name__)? Justify your answer?28
__name__ is a special variable that holds the name of the current module
Program execution starts from main or code with 0 indentation
__name__ has value __main__ in the above case. If the file is imported from another
module, __name__ holds the name of this module
What is a numpy array?29
A numpy array is a grid of values, all of
the same type, and is indexed by a
tuple of nonnegative integers
The number of dimensions is the rank
of the array
The shape of an array is a tuple of integers
giving the size of the array along each
dimension1
2
3
What is the difference between matrices and arrays?30
• An array is a sequence of objects of similar data type
• An array within another array forms a matrix
Matrices Arrays
• A matrix comes from linear algebra and is a two
dimensional representation of data
• It comes with a powerful set of mathematical
operations that allows you to manipulate the data
in interesting ways
How to get indices of N maximum values in a NumPy array?31
>>import numpy as np
>>arr=np.array([1,3,2,4,5])
>>print(arr.argsort()[-N:][::-1])
How would you obtain the res_set from the train_set and test_set?32
>>train_set=np.array([1,2,3])
>>test_set=np.array([[0,1,2],[1,2,3]
res_set [[1,2,3],[0,1,2],[1,2,3]]
A res_set = train_set.append(test_set)
B res_set = np.concatenate([train_set, test_set]))
C resulting_set = np.vstack([train_set, test_set])
D None of these
>>train_set=np.array([1,2,3])
>>test_set=np.array([[0,1,2],[1,2,3]
res_set [[1,2,3],[0,1,2],[1,2,3]]
A res_set = train_set.append(test_set)
B res_set = np.concatenate([train_set, test_set]))
C resulting_set = np.vstack([train_set, test_set])
D None of these
How would you obtain the res_set from the train_set and test_set?32
32
>>train_set=np.array([1,2,3])
>>test_set=np.array([[0,1,2],[1,2,3]
res_set [[1,2,3],[0,1,2],[1,2,3]]
A res_set = train_set.append(test_set)
B res_set = np.concatenate([train_set, test_set]))
C resulting_set = np.vstack([train_set, test_set])
D None of these
Both option A and B would do horizontal stacking, but we would like
to have vertical stacking. Option C does just this
How would you obtain the res_set from the train_set and test_set?32
How would you import a decision tree classifier in sklearn?33
A from sklearn.decision_tree import DecisionTreeClassifier
B from sklearn.ensemble import DecisionTreeClassifier
C
D
from sklearn.tree import DecisionTreeClassifier
None of these
A from sklearn.decision_tree import DecisionTreeClassifier
B from sklearn.ensemble import DecisionTreeClassifier
C
D
from sklearn.tree import DecisionTreeClassifier
None of these
How would you import a decision tree classifier in sklearn?33
34
You have uploaded the dataset in csv format on Google spreadsheet and shared it publicly.
How can you access this in Python?
>>link = https://docs.google.com/spreadsheets/d/...
>>source = StringIO.StringIO(requests.get(link).content))
>>data = pd.read_csv(source)
What is the difference between the two data series given below?35
df[‘Name’] and df.loc[:, ‘Name’], where:
df = pd.DataFrame(['aa', 'bb', 'xx', 'uu'], [21, 16, 50, 33], columns = ['Name', 'Age'])
A 1 is view of original dataframe and 2 is a copy of original dataframe
B 2 is view of original dataframe and 1 is a copy of original dataframe
C
D
Both are copies of original dataframe
Both are views of original dataframe
What is the difference between the two data series given below?35
df[‘Name’] and df.loc[:, ‘Name’], where:
df = pd.DataFrame(['aa', 'bb', 'xx', 'uu'], [21, 16, 50, 33], columns = ['Name', 'Age'])
A 1 is view of original dataframe and 2 is a copy of original dataframe
B 2 is view of original dataframe and 1 is a copy of original dataframe
C
D
Both are copies of original dataframe
Both are views of original dataframe
36
A pd.read_csv(“temp.csv”, compression=’gzip’)
B pd.read_csv(“temp.csv”, dialect=’str’)
C
D
pd.read_csv(“temp.csv”, encoding=’utf-8′)
None of these
Error:
Traceback (most recent call last): File "<input>", line 1, in<module> UnicodeEncodeError:
'ascii' codec can't encode character.
You get the following error while trying to read a file “temp.csv” using pandas. Which of the
following could correct it?
36
A pd.read_csv(“temp.csv”, compression=’gzip’)
B pd.read_csv(“temp.csv”, dialect=’str’)
C
D
pd.read_csv(“temp.csv”, encoding=’utf-8′)
None of these
You get the following error while trying to read a file “temp.csv” using pandas. Which of the
following could correct it?
Error:
Traceback (most recent call last): File "<input>", line 1, in<module> UnicodeEncodeError:
'ascii' codec can't encode character.
encoding should be ‘utf-8’
How to set a line width in the plot given below?37
A In line two, write plt.plot([1,2,3,4], width=3)
B In line two, write plt.plot([1,2,3,4], line_width=3
C
D
In line two, write plt.plot([1,2,3,4], lw=3)
None of these >>import matplotlib.pyplot as plt
>>plt.plot([1,2,3,4])
>>plt.show()
How to set a line width in the plot given below?37
A In line two, write plt.plot([1,2,3,4], width=3)
B In line two, write plt.plot([1,2,3,4], line_width=3
C
D
In line two, write plt.plot([1,2,3,4], lw=3)
None of these >>import matplotlib.pyplot as plt
>>plt.plot([1,2,3,4])
>>plt.show()
How would you reset the index of a dataframe to a given list?38
A df.reset_index(new_index,)
B df.reindex(new_index,)
C df.reindex_like(new_index,)
None of theseD
How would you reset the index of a dataframe to a given list?38
A df.reset_index(new_index,)
B df.reindex(new_index,)
C df.reindex_like(new_index,)
None of theseD
How can you copy objects in Python?39
Business
Analyst
copy.copy () for shallow copy copy.deepcopy () for deep copy
The functions used to copy objects in Python are-
What is the difference between range () and xrange () functions in Python?40
• xrange returns an xrange object
• xrange creates values as you need them through
yielding
Matrices Arrays
• range returns a Python list object
• xrange returns an xrange object
How can you check whether a pandas data frame is empty or not?41
The attribute df.empty is used to check whether a pandas data frame
is empty or not
>>import pandas as pd
>>df=pd.DataFrame({A:[]})
>>df.empty
Output: True
Write the code to sort an array in NumPy by the (n-1)th column?42
>>import numpy as np
>>X=np.array([[1,2,3],[0,5,2],[2,3,4]])
>>X[X[:,1].argsort()]
Output:array([[1,2,3],[0,5,2],[2,3,4]])
• This can be achieved using argsort() function
• Let us take an array X then to sort the (n-1)th column the code will be x[x [:
n-2].argsort()]
How to create a series from a list, numpy array and dictionary?43
Command PromptC:>_
>> #Input
>>import numpy as np
>>import pandas as pd
>>mylist = list('abcedfghijklmnopqrstuvwxyz’)
>>myarr = np.arange(26)
>>mydict = dict(zip(mylist, myarr))
>> #Solution
>>ser1 = pd.Series(mylist)
>>ser2 = pd.Series(myarr)
>>ser3 = pd.Series(mydict)
>>print(ser3.head())
How to get the items not common to both series A and series B?44
Command PromptC:>_
>> #Input
>>import pandas as pd
>>ser1 = pd.Series([1, 2, 3, 4, 5])
>>ser2 = pd.Series([4, 5, 6, 7, 8])
>> #Solution
>>ser_u = pd.Series(np.union1d(ser1, ser2)) # union
>>ser_i = pd.Series(np.intersect1d(ser1, ser2)) # intersect
>>ser_u[~ser_u.isin(ser_i)]
45
Command PromptC:>_
>> #Input
>>import pandas as pd
>>np.random.RandomState(100)
>>ser = pd.Series(np.random.randint(1, 5, [12]))
>> #Solution
>>print("Top 2 Freq:", ser.value_counts())
>>ser[~ser.isin(ser.value_counts().index[:2])] = 'Other’
>>ser
How to keep only the top 2 most frequent values as it is and replace everything else
as ‘Other’ in a series?
How to find the positions of numbers that are multiples of 3 from a series?46
Command PromptC:>_
>> #Input
>>import pandas as pd
>>ser = pd.Series(np.random.randint(1, 10, 7))
>>ser
>> #Solution
>>print(ser)
>>np.argwhere(ser % 3==0)
How to compute the Euclidean distance between two series?47
Command PromptC:>_
>> #Input
>>p = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>q = pd.Series([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
>> #Solution
>>sum((p - q)**2)**.5
>> #Solution using func
>>np.linalg.norm(p-q)
How to reverse the rows of a data frame?48
Command PromptC:>_
>> #Input
>>df = pd.DataFrame(np.arange(25).reshape(5, -1))
>> #Solution
>>df.iloc[::-1, :]
If you split your data into train/test splits, is it still possible to overfit your model?49
One common beginner mistake is re-tuning a model or training new models with
different parameters after seeing its performance on the test set
Yes, it's definitely
possible
Which python library is built on top of matplotlib and pandas to ease data plotting?50
Seaborn is a data visualization library in Python that provides a high level interface for
drawing statistical informative graphs
Seaborn!
Python Interview Questions | Python Interview Questions And Answers | Python Tutorial | Simplilearn

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
List in Python
List in PythonList in Python
List in Python
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Matplotlib
MatplotlibMatplotlib
Matplotlib
 
Skip list vinay khimsuriya_200430723005
Skip list vinay khimsuriya_200430723005Skip list vinay khimsuriya_200430723005
Skip list vinay khimsuriya_200430723005
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Boyer moore algorithm
Boyer moore algorithmBoyer moore algorithm
Boyer moore algorithm
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 

Semelhante a Python Interview Questions | Python Interview Questions And Answers | Python Tutorial | Simplilearn

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 

Semelhante a Python Interview Questions | Python Interview Questions And Answers | Python Tutorial | Simplilearn (20)

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
PYTHON
PYTHONPYTHON
PYTHON
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Python_IoT.pptx
Python_IoT.pptxPython_IoT.pptx
Python_IoT.pptx
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Advance python
Advance pythonAdvance python
Advance python
 
Python Training
Python TrainingPython Training
Python Training
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
 
Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 

Mais de Simplilearn

What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...
What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...
What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...
Simplilearn
 
Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...
Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...
Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...
Simplilearn
 
React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...
React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...
React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...
Simplilearn
 
Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...
Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...
Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...
Simplilearn
 
How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...
How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...
How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...
Simplilearn
 
Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...
Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...
Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...
Simplilearn
 
Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...
Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...
Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...
Simplilearn
 
Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...
Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...
Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...
Simplilearn
 
React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...
React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...
React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...
Simplilearn
 
What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...
What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...
What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...
Simplilearn
 
How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...
How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...
How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...
Simplilearn
 
WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...
WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...
WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...
Simplilearn
 
Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...
Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...
Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...
Simplilearn
 
How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...
How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...
How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...
Simplilearn
 
How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...
How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...
How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...
Simplilearn
 

Mais de Simplilearn (20)

ChatGPT in Cybersecurity
ChatGPT in CybersecurityChatGPT in Cybersecurity
ChatGPT in Cybersecurity
 
Whatis SQL Injection.pptx
Whatis SQL Injection.pptxWhatis SQL Injection.pptx
Whatis SQL Injection.pptx
 
Top 5 High Paying Cloud Computing Jobs in 2023
 Top 5 High Paying Cloud Computing Jobs in 2023  Top 5 High Paying Cloud Computing Jobs in 2023
Top 5 High Paying Cloud Computing Jobs in 2023
 
Types Of Cloud Jobs In 2024
Types Of Cloud Jobs In 2024Types Of Cloud Jobs In 2024
Types Of Cloud Jobs In 2024
 
Top 12 AI Technologies To Learn 2024 | Top AI Technologies in 2024 | AI Trend...
Top 12 AI Technologies To Learn 2024 | Top AI Technologies in 2024 | AI Trend...Top 12 AI Technologies To Learn 2024 | Top AI Technologies in 2024 | AI Trend...
Top 12 AI Technologies To Learn 2024 | Top AI Technologies in 2024 | AI Trend...
 
What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...
What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...
What is LSTM ?| Long Short Term Memory Explained with Example | Deep Learning...
 
Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...
Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...
Top 10 Chat GPT Use Cases | ChatGPT Applications | ChatGPT Tutorial For Begin...
 
React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...
React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...
React JS Vs Next JS - What's The Difference | Next JS Tutorial For Beginners ...
 
Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...
Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...
Backpropagation in Neural Networks | Back Propagation Algorithm with Examples...
 
How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...
How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...
How to Become a Business Analyst ?| Roadmap to Become Business Analyst | Simp...
 
Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...
Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...
Career Opportunities In Artificial Intelligence 2023 | AI Job Opportunities |...
 
Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...
Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...
Programming for Beginners | How to Start Coding in 2023? | Introduction to Pr...
 
Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...
Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...
Best IDE for Programming in 2023 | Top 8 Programming IDE You Should Know | Si...
 
React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...
React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...
React 18 Overview | React 18 New Features and Changes | React 18 Tutorial 202...
 
What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...
What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...
What Is Next JS ? | Introduction to Next JS | Basics of Next JS | Next JS Tut...
 
How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...
How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...
How To Become an SEO Expert In 2023 | SEO Expert Tutorial | SEO For Beginners...
 
WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...
WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...
WordPress Tutorial for Beginners 2023 | What Is WordPress and How Does It Wor...
 
Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...
Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...
Blogging For Beginners 2023 | How To Create A Blog | Blogging Tutorial | Simp...
 
How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...
How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...
How To Start A Blog In 2023 | Pros And Cons Of Blogging | Blogging Tutorial |...
 
How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...
How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...
How to Increase Website Traffic ? | 10 Ways To Increase Website Traffic in 20...
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Último (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

Python Interview Questions | Python Interview Questions And Answers | Python Tutorial | Simplilearn

  • 1.
  • 2. What is the difference between shallowcopy and deepcopy? 1 Child1 Child2 Child3 Object 1 Child1 Child2 Child3 Object 2 Deep copy creates a different object and populates it with the child objects of the original object. Therefore, changes in the original object is not reflected in the copy copy.deepcopy() creates a deep copy Child1 Child2 Child3 Object 1 Object 2 Shallow copy creates a different object and populates it with the references of the child objects within the original object. Therefore, changes in the original object is reflected in the copy copy.copy creates a shallow copy
  • 3. How is multithreading achieved in Python? 2 Multithreading usually implies that multiple threads are executed concurrently The Python Global Interpreter Lock doesn’t allow more than one thread to hold the Python interpreter at a particular point of time So, multithreading in Python is achieved through context switching
  • 4. Discuss the Django architecture 3 Model Template ViewURLDjangoUser Template: The front end of the webpage Model: The back end where the data is stored View: Interacts with the Model and Template and Maps it to a URL Django: Serves the page to the user
  • 5. What advantage does Numpy array have over nested list? 4 • Numpy is written in C such that all its complexities are packed into a simple-to-use module • Lists on the other hand are dynamically typed. Therefore, Python must check the data type of each element every time it uses it • This makes Numpy arrays much faster than lists Lists Array
  • 6. What is pickling and unpickling? 5 • Converting a byte stream to a Python object hierarchy is called unpickling • Unpickling is also referred to as deserialization Pickling Unpickling • Converting a Python object hierarchy to a byte stream is called pickling • Pickling is also referred to as serialization
  • 7. How is memory managed in Python? 6 • Python has a private heap space where it stores all the objects • The Python memory manager manages various aspects of this heap like sharing, caching, segmentation and allocation • The user has no control over the heap. Only the Python interpreter has this access Private Heap Garbage collector Memory manager Interpreter Program
  • 8. Are arguments in Python passed by value or by reference? 7 Arguments are passed in Python by reference. This means that any change made within a function is reflected on the original object def fun(l): l[0]=3 l=[1,2,3,4] fun(l) print(l) Output: [3,2,3,4] def fun(l): l=[3,2,3,4] l=[1,2,3,4] fun(l) print(l) Output: [1,2,3,4] Lists are mutable A new object is created
  • 9. How would you generate random numbers in Python? 8 To generate random numbers in Python, you must first import the random module > import random
  • 10. How would you generate random numbers in Python? 8 To generate random numbers in Python, you must first import the random module > import random The random() function generates a random float value between 0 and 1 > random.random()
  • 11. How would you generate random numbers in Python? 8 To generate random numbers in Python, you must first import the random module > import random The random() function generates a random float value between 0 and 1 > random.random() The randrange() function generates a random number within a given range > random.randrange(1,10,2) Syntax: randrange(beginning, end, step)
  • 12. What does the // operator do? 9 In Python, the / operator performs division and returns the quotient in float For example: 5/2 returns 2.5 The // operator on the other hand, returns the quotient in integer For example: 5//2 returns 2
  • 13. What does the “is” operator do? 1 0 The “is” operator compares the id of the two objects list1=[1,2,3] list2=[1,2,3] list3=list1 list1 == list2  True list1 is list2  False list1 is list3  True
  • 14. What is the purpose of pass statement? 1 1 var="Si mplilea rn" for i in var: if i==" ": pass else: print(i,end="") No action is required The pass statement is used when there’s a syntactic but not an operational requirement For example: The program below prints a string ignoring the spaces
  • 15. How will you check if all characters in a string are alphanumeric? 1 2 • Python has an in built method isalnum() which returns true if all characters in the string are alphanumeric >> "abcd123".isalnum() Output: True >>”abcd@123#”.isalnum() Output: False
  • 16. How will you check if all characters in a string are alphanumeric? 1 2 • Python has an in built method isalnum() which returns true if all characters in the string are alphanumeric • One can also use regex instead >>import re >>bool(re.match(‘[A-Za-z0-9]+$','abcd123’)) Output: True >> bool(re.match(‘[A-Za-z0-9]+$','abcd@123’)) Output: False
  • 17. How will you merge elements in a sequence? 1 3 Sequence There are three types of sequences in Python: • Lists • Tuples • Strings
  • 18. How will you merge elements in a sequence? 1 3 Sequence There are three types of sequences in Python: • Lists • Tuples • Strings >>l1=[1,2,3] >>l2=[4,5,6] >>l1+l2 Output: [1,2,3,4,5,6]
  • 19. How will you merge elements in a sequence? 1 3 Sequence There are three types of sequences in Python: • Lists • Tuples • Strings >>t1=(1,2,3) >>t2=(4,5,6) >>t1+t2 Output: (1,2,3,4,5,6)
  • 20. How will you merge elements in a sequence? 1 3 Sequence There are three types of sequences in Python: • Lists • Tuples • Strings >>s1=“Simpli” >>s2=“learn” >>s1+s2 Output: ‘Simplilearn’
  • 21. How will you remove all leading whitespaces in string? 1 4 Python provides the in built function lstrip(), to remove all leading spaces from a string >>“ Python”.lstrip Output: Python
  • 22. How will you replace all occurrences of a substring with a new string? 1 5 The replace() function can be used with strings for replacing a substring with a given string >>"Hey John. How are you, john?".replace(“john",“John",1) Output: “Hey John. How are you, john?” Syntax: str.replace(old, new, count) replace() returns a new string without modifying the original one
  • 23. What is the difference between del and remove() on lists? 1 6 del • del removes all elements of a list within a given range • Syntax: del list[start:end] remove() • remove() removes the first occurrence of a particular character • Syntax: list.remove(element) del • del removes all elements of a list within a given range • Syntax: del list[start:end] >>lis=[‘a’,’b’,’c’,’d ’] >>del lis[1:3] >>lis Output: [“a”,”d”] >>lis=[‘a’,’b’,’b’,’d ’] >>lis.remove(‘b’) >>lis Output: [‘a’,’b’,’d’]
  • 24. How to display the contents of text file in reverse order? 1 7 Open the file using the open() function Store the contents of the file into a list Reverse the contents of this list Run a for loop to iterate through the list
  • 25. Differentiate between append() and extend() 1 8 extend()append() • Append() adds an element to the end of the list • extend() adds elements from an iterable to the end of the list >>lst=[1,2,3] >>lst.append(4) >>lst Output:[1,2,3,4] >>lst=[1,2,3] >>lst.extend([4,5,6]) >>lst Output:[1,2,3,4,5,6]
  • 26. What’s the output of the below code? Justify your answer 1 9 >>def addToList(val, list=[]): >> list.append(val) >> return list >>list1 = addToList(1) >>list2 = addToList(123,[]) >>list3 = addToList('a’) >>print ("list1 = %s" % list1) >>print ("list2 = %s" % list2) >>print ("list3 = %s" % list3) list1 = [1,’a’] list2 = [123] lilst3 = [1,’a’] Output
  • 27. What’s the output of the below code? Justify your answer 1 9 >>def addToList(val, list=[]): >> list.append(val) >> return list >>list1 = addToList(1) >>list2 = addToList(123,[]) >>list3 = addToList('a’) >>print ("list1 = %s" % list1) >>print ("list2 = %s" % list2) >>print ("list3 = %s" % list3) list1 = [1,’a’] list2 = [123] lilst3 = [1,’a’] Output Default list is created only once during function creation and not during its call
  • 28. What is the difference between a list and a tuple?20 Lists are mutable while tuples are immutable >>lst = [1,2,3] >>lst[2] = 4 >>lst Output:[1,2,4] >>tpl = (1,2,3) >>tpl[2] = 4 >>tpl Output:TypeError: 'tuple' object does not support item assignment List Tuple
  • 29. What is docstring in python?21 Docstrings are used in providing documentation to various Python modules classes, functions and methods def add(a,b): """This function adds two numbers.""" sum=a+b return sum sum=add(10,20) print("Accessing doctstring method 1:",add.__doc__) print("Accessing doctstring method 2:",end="") help(add) This is a docstring
  • 30. What is docstring in python?21 Docstrings are used in providing documentation to various Python modules classes, functions and methods def add(a,b): """This function adds two numbers.""" sum=a+b return sum sum=add(10,20) print("Accessing doctstring method 1:",add.__doc__) print("Accessing doctstring method 2:",end="") help(add) This is a docstring Accessing doctstring method 1: This function adds two numbers. Accessing doctstring method 2: Help on function add in module __main__: add(a, b) This function adds two numbers. Output:
  • 31. How do you use print() without the newline?22 The solution to this is dependent on the Python version you are using >>print(“Hi.”), >>print(“How are you?”) Output: Hi. How are you? >>print(“Hi”,end=“ ”) >>print(“How are you?”) Output: Hi. How are you? Python 2 Python 3
  • 32. How do you use the split() function in Python?23 The split() function splits a string into a number of strings based on a specified delimiter string.split(delimiter,max) The character based on which the string is split. By default it’s space The maximum number of splits
  • 33. The maximum number of splits How do you use the split() function in Python?23 The split() function splits a string into a number of strings based on a specified delimiter string.split(delimiter,max) The character based on which the string is split. Default is space >>var=“Red,Blue,Green,Orange” >>lst=var.split(“,”,2) >>print(lst) Output: [‘Red’,’Blue’,’Green,Orange’]
  • 34. Is Python object oriented or functional programming?24 Python follows Object Oriented Paradigm • Python allows the creation of objects and its manipulation through specific methods • It supports most of the features of OOPs such as inheritance an polymorphism Python follows Functional Programming paradigm • Functions may be used as first class object • Python supports Lambda functions which are characteristic of functional paradigm
  • 35. Write a function prototype that takes variable number of arguments25 >>def fun(*var): >> for i in var: >> print(i) >>fun(1) >>fun(1,25,6) def function_name(*list)
  • 36. What is *args and **kwargs?26 *args **kwargs Used in function prototype to accept varying number of arguments It’s an iterable object def fun(*args) Used in function prototype to accept varying number of keyworded arguments It’s an iterable object def fun(**kwargs): ...... fun( colour=“red”,units=2)
  • 37. "In Python, functions are first class objects" What do you understand from this?27 A function can be treated just like an object You can assign them to variablesYou can pass them as arguments to other functions You can return them from other functions
  • 38. What is the output of : print(__name__)? Justify your answer?28 __name__ is a special variable that holds the name of the current module Program execution starts from main or code with 0 indentation __name__ has value __main__ in the above case. If the file is imported from another module, __name__ holds the name of this module
  • 39. What is a numpy array?29 A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers The number of dimensions is the rank of the array The shape of an array is a tuple of integers giving the size of the array along each dimension1 2 3
  • 40. What is the difference between matrices and arrays?30 • An array is a sequence of objects of similar data type • An array within another array forms a matrix Matrices Arrays • A matrix comes from linear algebra and is a two dimensional representation of data • It comes with a powerful set of mathematical operations that allows you to manipulate the data in interesting ways
  • 41. How to get indices of N maximum values in a NumPy array?31 >>import numpy as np >>arr=np.array([1,3,2,4,5]) >>print(arr.argsort()[-N:][::-1])
  • 42. How would you obtain the res_set from the train_set and test_set?32 >>train_set=np.array([1,2,3]) >>test_set=np.array([[0,1,2],[1,2,3] res_set [[1,2,3],[0,1,2],[1,2,3]] A res_set = train_set.append(test_set) B res_set = np.concatenate([train_set, test_set])) C resulting_set = np.vstack([train_set, test_set]) D None of these
  • 43. >>train_set=np.array([1,2,3]) >>test_set=np.array([[0,1,2],[1,2,3] res_set [[1,2,3],[0,1,2],[1,2,3]] A res_set = train_set.append(test_set) B res_set = np.concatenate([train_set, test_set])) C resulting_set = np.vstack([train_set, test_set]) D None of these How would you obtain the res_set from the train_set and test_set?32
  • 44. 32 >>train_set=np.array([1,2,3]) >>test_set=np.array([[0,1,2],[1,2,3] res_set [[1,2,3],[0,1,2],[1,2,3]] A res_set = train_set.append(test_set) B res_set = np.concatenate([train_set, test_set])) C resulting_set = np.vstack([train_set, test_set]) D None of these Both option A and B would do horizontal stacking, but we would like to have vertical stacking. Option C does just this How would you obtain the res_set from the train_set and test_set?32
  • 45. How would you import a decision tree classifier in sklearn?33 A from sklearn.decision_tree import DecisionTreeClassifier B from sklearn.ensemble import DecisionTreeClassifier C D from sklearn.tree import DecisionTreeClassifier None of these
  • 46. A from sklearn.decision_tree import DecisionTreeClassifier B from sklearn.ensemble import DecisionTreeClassifier C D from sklearn.tree import DecisionTreeClassifier None of these How would you import a decision tree classifier in sklearn?33
  • 47. 34 You have uploaded the dataset in csv format on Google spreadsheet and shared it publicly. How can you access this in Python? >>link = https://docs.google.com/spreadsheets/d/... >>source = StringIO.StringIO(requests.get(link).content)) >>data = pd.read_csv(source)
  • 48. What is the difference between the two data series given below?35 df[‘Name’] and df.loc[:, ‘Name’], where: df = pd.DataFrame(['aa', 'bb', 'xx', 'uu'], [21, 16, 50, 33], columns = ['Name', 'Age']) A 1 is view of original dataframe and 2 is a copy of original dataframe B 2 is view of original dataframe and 1 is a copy of original dataframe C D Both are copies of original dataframe Both are views of original dataframe
  • 49. What is the difference between the two data series given below?35 df[‘Name’] and df.loc[:, ‘Name’], where: df = pd.DataFrame(['aa', 'bb', 'xx', 'uu'], [21, 16, 50, 33], columns = ['Name', 'Age']) A 1 is view of original dataframe and 2 is a copy of original dataframe B 2 is view of original dataframe and 1 is a copy of original dataframe C D Both are copies of original dataframe Both are views of original dataframe
  • 50. 36 A pd.read_csv(“temp.csv”, compression=’gzip’) B pd.read_csv(“temp.csv”, dialect=’str’) C D pd.read_csv(“temp.csv”, encoding=’utf-8′) None of these Error: Traceback (most recent call last): File "<input>", line 1, in<module> UnicodeEncodeError: 'ascii' codec can't encode character. You get the following error while trying to read a file “temp.csv” using pandas. Which of the following could correct it?
  • 51. 36 A pd.read_csv(“temp.csv”, compression=’gzip’) B pd.read_csv(“temp.csv”, dialect=’str’) C D pd.read_csv(“temp.csv”, encoding=’utf-8′) None of these You get the following error while trying to read a file “temp.csv” using pandas. Which of the following could correct it? Error: Traceback (most recent call last): File "<input>", line 1, in<module> UnicodeEncodeError: 'ascii' codec can't encode character. encoding should be ‘utf-8’
  • 52. How to set a line width in the plot given below?37 A In line two, write plt.plot([1,2,3,4], width=3) B In line two, write plt.plot([1,2,3,4], line_width=3 C D In line two, write plt.plot([1,2,3,4], lw=3) None of these >>import matplotlib.pyplot as plt >>plt.plot([1,2,3,4]) >>plt.show()
  • 53. How to set a line width in the plot given below?37 A In line two, write plt.plot([1,2,3,4], width=3) B In line two, write plt.plot([1,2,3,4], line_width=3 C D In line two, write plt.plot([1,2,3,4], lw=3) None of these >>import matplotlib.pyplot as plt >>plt.plot([1,2,3,4]) >>plt.show()
  • 54. How would you reset the index of a dataframe to a given list?38 A df.reset_index(new_index,) B df.reindex(new_index,) C df.reindex_like(new_index,) None of theseD
  • 55. How would you reset the index of a dataframe to a given list?38 A df.reset_index(new_index,) B df.reindex(new_index,) C df.reindex_like(new_index,) None of theseD
  • 56. How can you copy objects in Python?39 Business Analyst copy.copy () for shallow copy copy.deepcopy () for deep copy The functions used to copy objects in Python are-
  • 57. What is the difference between range () and xrange () functions in Python?40 • xrange returns an xrange object • xrange creates values as you need them through yielding Matrices Arrays • range returns a Python list object • xrange returns an xrange object
  • 58. How can you check whether a pandas data frame is empty or not?41 The attribute df.empty is used to check whether a pandas data frame is empty or not >>import pandas as pd >>df=pd.DataFrame({A:[]}) >>df.empty Output: True
  • 59. Write the code to sort an array in NumPy by the (n-1)th column?42 >>import numpy as np >>X=np.array([[1,2,3],[0,5,2],[2,3,4]]) >>X[X[:,1].argsort()] Output:array([[1,2,3],[0,5,2],[2,3,4]]) • This can be achieved using argsort() function • Let us take an array X then to sort the (n-1)th column the code will be x[x [: n-2].argsort()]
  • 60. How to create a series from a list, numpy array and dictionary?43 Command PromptC:>_ >> #Input >>import numpy as np >>import pandas as pd >>mylist = list('abcedfghijklmnopqrstuvwxyz’) >>myarr = np.arange(26) >>mydict = dict(zip(mylist, myarr)) >> #Solution >>ser1 = pd.Series(mylist) >>ser2 = pd.Series(myarr) >>ser3 = pd.Series(mydict) >>print(ser3.head())
  • 61. How to get the items not common to both series A and series B?44 Command PromptC:>_ >> #Input >>import pandas as pd >>ser1 = pd.Series([1, 2, 3, 4, 5]) >>ser2 = pd.Series([4, 5, 6, 7, 8]) >> #Solution >>ser_u = pd.Series(np.union1d(ser1, ser2)) # union >>ser_i = pd.Series(np.intersect1d(ser1, ser2)) # intersect >>ser_u[~ser_u.isin(ser_i)]
  • 62. 45 Command PromptC:>_ >> #Input >>import pandas as pd >>np.random.RandomState(100) >>ser = pd.Series(np.random.randint(1, 5, [12])) >> #Solution >>print("Top 2 Freq:", ser.value_counts()) >>ser[~ser.isin(ser.value_counts().index[:2])] = 'Other’ >>ser How to keep only the top 2 most frequent values as it is and replace everything else as ‘Other’ in a series?
  • 63. How to find the positions of numbers that are multiples of 3 from a series?46 Command PromptC:>_ >> #Input >>import pandas as pd >>ser = pd.Series(np.random.randint(1, 10, 7)) >>ser >> #Solution >>print(ser) >>np.argwhere(ser % 3==0)
  • 64. How to compute the Euclidean distance between two series?47 Command PromptC:>_ >> #Input >>p = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) >>q = pd.Series([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) >> #Solution >>sum((p - q)**2)**.5 >> #Solution using func >>np.linalg.norm(p-q)
  • 65. How to reverse the rows of a data frame?48 Command PromptC:>_ >> #Input >>df = pd.DataFrame(np.arange(25).reshape(5, -1)) >> #Solution >>df.iloc[::-1, :]
  • 66. If you split your data into train/test splits, is it still possible to overfit your model?49 One common beginner mistake is re-tuning a model or training new models with different parameters after seeing its performance on the test set Yes, it's definitely possible
  • 67. Which python library is built on top of matplotlib and pandas to ease data plotting?50 Seaborn is a data visualization library in Python that provides a high level interface for drawing statistical informative graphs Seaborn!

Notas do Editor

  1. Style - 01
  2. Style - 01
  3. Style - 01
  4. Style - 01
  5. Style - 01
  6. Style - 01
  7. Style - 01
  8. Style - 01
  9. Style - 01
  10. Style - 01
  11. Style - 01
  12. Style - 01
  13. Style - 01
  14. Style - 01
  15. Style - 01
  16. Style - 01
  17. Style - 01
  18. Style - 01
  19. Style - 01
  20. Style - 01
  21. Style - 01
  22. Style - 01
  23. Style - 01
  24. Style - 01
  25. Style - 01
  26. Style - 01
  27. Style - 01
  28. Style - 01
  29. Style - 01
  30. Style - 01
  31. Style - 01
  32. Style - 01
  33. Style - 01
  34. Style - 01
  35. Style - 01
  36. Style - 01
  37. Style - 01
  38. Style - 01
  39. Style - 01
  40. Style - 01
  41. Style - 01
  42. Style - 01
  43. Style - 01
  44. Style - 01
  45. Style - 01
  46. Style - 01
  47. Style - 01
  48. Style - 01
  49. Style - 01
  50. Style - 01
  51. Style - 01
  52. Style - 01
  53. Style - 01
  54. Style - 01
  55. Style - 01
  56. Style - 01
  57. Style - 01
  58. Style - 01
  59. Style - 01
  60. Style - 01
  61. Style - 01
  62. Style - 01
  63. Style - 01
  64. Style - 01
  65. Style - 01
  66. Style - 01