What Is The Command To Debug A Python Program?
The following command helps run a Python program in debug mode.
$ python -m pdb python-script.py
Why And When Do You Use Generators In Python?
A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.
We can replace loops with generators for efficiently calculating results involving large data sets.
Generators are useful when we don’t want all the results and wish to hold back for some time.
Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.
How will you remove an object from a list?
list.remove(obj) − Removes object obj from list.
How will you reverse a list?
list.reverse() − Reverses objects of list in place.
What Does The <Yield> Keyword Do In Python?
The <yield> keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a function can have multiple calls to the <yield> keyword.
See the example below.
def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
output: sun mon
How To Convert A List Into Other Data Types?
Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.
Turn A List Into A String.
We can use the <”.join()> method which combines all elements into one and returns as a string.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)
output: sun mon tue wed thu fri sat
Turn A List Into A Tuple.
Call Python’s <tuple()> function for converting a list into a tuple. This function takes the list as its argument. But remember, we can’t change the list after turning it into a tuple because it becomes immutable.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)
output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
Turn A List Into A Set.
Converting a list to a set poses two side-effects.
Set doesn’t allow duplicate entries, so the conversion will remove any such item if found.
A set is an ordered collection, so the order of list items would also change.
However, we can use the <set()> function to convert a list to a set.
weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)
output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])
Turn A List Into A Dictionary.
In a dictionary, each item represents a key-value pair. So converting a list isn’t as straight forward as it were for other data types.
However, we can achieve the conversion by breaking the list into a set of pairs and then call the <zip()> function to return them as tuples.
Passing the tuples into the <dict()> function would finally turn them into a dictionary.
weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}
How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?
Unlike sets, lists can have items with same values. In Python, the list has a <count()> function which returns the occurrences of a particular item.
Count The Occurrences Of An Individual Item.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))
output: 3
What Is NumPy And How Is It Better Than A List In Python?
NumPy is a Python package for scientific computing which can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.
Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.
NumPy arrays are more compact than lists.
Reading and writing items is faster with NumPy.
Using NumPy is more convenient than to the standard list.
NumPy arrays are more efficient as they augment the functionality of lists in Python.
What Are Different Ways To Create An Empty NumPy Array In Python?
There are two methods which we can apply to create empty NumPy arrays.
The First Method To Create An Empty Array.
import numpy
numpy.array([])
The Second Method To Create An Empty Array.
# Make an empty NumPy array
numpy.empty(shape=(0,0)).
What are the ways to write a function using call by reference?
Arguments in python are passed as an assignment. This assignment creates an object that has no relationship between an argument name in source and target. The procedure to write the function using call by reference includes:
The tuple result can be returned to the object which called it. The example below shows it:
def function(a, b):
a = 'value'
b = b + 1
# a and b are local variables that are used to assign the new objects
return a, b
# This is the function that is used to return the value stored in b
- The use of global variables allows the function to be called as reference but this is not the safe method to call any function.
- The use of mutable (they are the classes that consists of changeable objects) objects are used to pass the function by reference.
def function(a):
a[0] = 'string'
a[1] = a[1] + 1
# The ‘a’ array give reference to the mutable list and it changes the changes that are shared
args = ['string', 10]
func1(args)
print args[0], args[1]
#This prints the value stored in the array of ‘a’
How will you convert an integer to an unicode character in python?
unichr(x) − Converts an integer to a Unicode character.
How will you convert a single character to its integer value in python?
ord(x) − Converts a single character to its integer value.
How will you convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.
How will you convert an integer to octal string in python?
oct(x) − Converts an integer to an octal string.
What are the commands that are used to copy an object in Python?
The command that is used to copy an object in python includes:
- copy.copy() function: This makes a copy of the file from source to destination. It returns a shallow copy of the parameter that is passed.
- copy.deepcopy(): This also creates a copy of the object from source to destination. It returns a deep copy of the parameter that is passed to the function.
The dictionary consists of all the objects and the copy() method which is used as:
newdict = olddict.copy()
The assignment statement doesn’t copy any object but it creates a binding between the target and the object that is used for the mutable items. Copy is required to keep a copy of it using the modules that is provided to give generic and shallow operations.
What is the difference between deep and shallow copy?
- Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Whereas, deep copy is used to store the values that are already copied.
- Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Whereas, deep copy doesn’t copy the reference pointers to the objects. Deep copy makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object.
- Shallow copy allows faster execution of the program and it depends on the size of the data that is used. Whereas, deep copy makes it slower due to making certain copies for each object that is been called.
Write a program to find out the name of an object in python.
The object doesn’t have any name and there is no way the can be found out for objects. The assignment is used to bind a name to the value that includes the name of the object that has to be bound by a value. If the value is callable then the statements are made true and then the program followed can be used to find the reference name of an object.
class try:
pass
B = A
a = B()
b = a
print b
<__main__.try instance at 0x16D07CC>
print b
The class consists of name and the names are invoked by using the the variable B that creates an instance for the class try. The method is to find out from all the namespaces that the object exists and then print the name of the object.
How can the ternary operators be used in python?
The ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. The operator will be given as:
[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y
This is the lowest priority operator that is used in making a decision that is based on the values of true or false. The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.
How the string does get converted to a number?
- To convert the string into a number the built-in functions are used like int() constructor. It is a data type that is used like int (‘1’) ==1.
- float() is also used to show the number in the format as float(‘1’)=1.
- The number by default are interpreted as decimal and if it is represented by int(‘0x1’) then it gives an error as ValueError. In this the int(string,base) function takes the parameter to convert string to number in this the process will be like int(‘0x1’,16)==16. If the base parameter is defined as 0 then it is indicated by an octal and 0x indicates it as hexadecimal number.
- There is function eval() that can be used to convert string into number but it is a bit slower and present many security risks like __import__('os').system("rm -rf$HOME") - use of this will delete the home directory of the system.
What is the function of negative index?
The sequences in python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ as first index and ‘1’ as the second index and the process goes on like that. The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.
The following command helps run a Python program in debug mode.
$ python -m pdb python-script.py
Why And When Do You Use Generators In Python?
A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.
Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.
We can replace loops with generators for efficiently calculating results involving large data sets.
Generators are useful when we don’t want all the results and wish to hold back for some time.
Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.
How will you remove an object from a list?
list.remove(obj) − Removes object obj from list.
How will you reverse a list?
list.reverse() − Reverses objects of list in place.
What Does The <Yield> Keyword Do In Python?
The <yield> keyword can turn any function into a generator. It works like a standard return keyword. But it’ll always return a generator object. Also, a function can have multiple calls to the <yield> keyword.
See the example below.
def testgen(index):
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
output: sun mon
How To Convert A List Into Other Data Types?
Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.
Turn A List Into A String.
We can use the <”.join()> method which combines all elements into one and returns as a string.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsString = ' '.join(weekdays)
print(listAsString)
output: sun mon tue wed thu fri sat
Turn A List Into A Tuple.
Call Python’s <tuple()> function for converting a list into a tuple. This function takes the list as its argument. But remember, we can’t change the list after turning it into a tuple because it becomes immutable.
weekdays = ['sun','mon','tue','wed','thu','fri','sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)
output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
Turn A List Into A Set.
Converting a list to a set poses two side-effects.
Set doesn’t allow duplicate entries, so the conversion will remove any such item if found.
A set is an ordered collection, so the order of list items would also change.
However, we can use the <set()> function to convert a list to a set.
weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']
listAsSet = set(weekdays)
print(listAsSet)
output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])
Turn A List Into A Dictionary.
In a dictionary, each item represents a key-value pair. So converting a list isn’t as straight forward as it were for other data types.
However, we can achieve the conversion by breaking the list into a set of pairs and then call the <zip()> function to return them as tuples.
Passing the tuples into the <dict()> function would finally turn them into a dictionary.
weekdays = ['sun','mon','tue','wed','thu','fri']
listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))
print(listAsDict)
output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}
How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?
Unlike sets, lists can have items with same values. In Python, the list has a <count()> function which returns the occurrences of a particular item.
Count The Occurrences Of An Individual Item.
weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']
print(weekdays.count('mon'))
output: 3
What Is NumPy And How Is It Better Than A List In Python?
NumPy is a Python package for scientific computing which can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.
Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.
NumPy arrays are more compact than lists.
Reading and writing items is faster with NumPy.
Using NumPy is more convenient than to the standard list.
NumPy arrays are more efficient as they augment the functionality of lists in Python.
What Are Different Ways To Create An Empty NumPy Array In Python?
There are two methods which we can apply to create empty NumPy arrays.
The First Method To Create An Empty Array.
import numpy
numpy.array([])
The Second Method To Create An Empty Array.
# Make an empty NumPy array
numpy.empty(shape=(0,0)).
What are the ways to write a function using call by reference?
Arguments in python are passed as an assignment. This assignment creates an object that has no relationship between an argument name in source and target. The procedure to write the function using call by reference includes:
The tuple result can be returned to the object which called it. The example below shows it:
def function(a, b):
a = 'value'
b = b + 1
# a and b are local variables that are used to assign the new objects
return a, b
# This is the function that is used to return the value stored in b
- The use of global variables allows the function to be called as reference but this is not the safe method to call any function.
- The use of mutable (they are the classes that consists of changeable objects) objects are used to pass the function by reference.
def function(a):
a[0] = 'string'
a[1] = a[1] + 1
# The ‘a’ array give reference to the mutable list and it changes the changes that are shared
args = ['string', 10]
func1(args)
print args[0], args[1]
#This prints the value stored in the array of ‘a’
How will you convert an integer to an unicode character in python?
unichr(x) − Converts an integer to a Unicode character.
How will you convert a single character to its integer value in python?
ord(x) − Converts a single character to its integer value.
How will you convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.
How will you convert an integer to octal string in python?
oct(x) − Converts an integer to an octal string.
The command that is used to copy an object in python includes:
- copy.copy() function: This makes a copy of the file from source to destination. It returns a shallow copy of the parameter that is passed.
- copy.deepcopy(): This also creates a copy of the object from source to destination. It returns a deep copy of the parameter that is passed to the function.
The dictionary consists of all the objects and the copy() method which is used as:
newdict = olddict.copy()
The assignment statement doesn’t copy any object but it creates a binding between the target and the object that is used for the mutable items. Copy is required to keep a copy of it using the modules that is provided to give generic and shallow operations.
What is the difference between deep and shallow copy?
- Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Whereas, deep copy is used to store the values that are already copied.
- Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Whereas, deep copy doesn’t copy the reference pointers to the objects. Deep copy makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object.
- Shallow copy allows faster execution of the program and it depends on the size of the data that is used. Whereas, deep copy makes it slower due to making certain copies for each object that is been called.
Write a program to find out the name of an object in python.
The object doesn’t have any name and there is no way the can be found out for objects. The assignment is used to bind a name to the value that includes the name of the object that has to be bound by a value. If the value is callable then the statements are made true and then the program followed can be used to find the reference name of an object.
class try:
pass
B = A
a = B()
b = a
print b
<__main__.try instance at 0x16D07CC>
print b
The class consists of name and the names are invoked by using the the variable B that creates an instance for the class try. The method is to find out from all the namespaces that the object exists and then print the name of the object.
How can the ternary operators be used in python?
The ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. The operator will be given as:
[on_true] if [expression] else [on_false]
x, y = 25, 50
big = x if x < y else y
This is the lowest priority operator that is used in making a decision that is based on the values of true or false. The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.
How the string does get converted to a number?
- To convert the string into a number the built-in functions are used like int() constructor. It is a data type that is used like int (‘1’) ==1.
- float() is also used to show the number in the format as float(‘1’)=1.
- The number by default are interpreted as decimal and if it is represented by int(‘0x1’) then it gives an error as ValueError. In this the int(string,base) function takes the parameter to convert string to number in this the process will be like int(‘0x1’,16)==16. If the base parameter is defined as 0 then it is indicated by an octal and 0x indicates it as hexadecimal number.
- There is function eval() that can be used to convert string into number but it is a bit slower and present many security risks like __import__('os').system("rm -rf$HOME") - use of this will delete the home directory of the system.
What is the function of negative index?
The sequences in python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ as first index and ‘1’ as the second index and the process goes on like that. The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.
Post a Comment