Programming and Problem Solving through Python

Sequence data types in python Question & Answer



Question : 1
How many types of sequences are supported in Python?


Answer :

Three Types of Sequences are supported in python:

(i) String

(ii) List

(iii) Tuple



Question : 2
What are nested Lists?


Answer :

A list can have an element in it, which itself is a list. Such a list is called nested list. e.g.

L = [1,2,3,4,[5,6,7],8]



Question : 3
Discuss the utility and significance of Lists.


Answer :

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. List is majorly used with dictionaries when there is large number of data.



Question : 4
What is the purpose of the del operator and pop method? Try deleting a slice.


Answer :

del operator is used to remove an individual item, or to remove all items identified by a slice. It is to be used as per syntax given below –

>>>del List[index]

>>>del List[start:stop]

pop method is used to remove single element, not list slices. The pop() method removes an individual item and returns it. Its syntax is –

>>>a=List.pop() #this will remove last item and deleted item will be assigned to a.

>>>a=List[10] # this will remove the ite at index 10 and deleted item will be assigned to a.



Question : 5
What are list slices?


Answer :

List slices, like string slices are the sub part of a list extracted out. Indexes can be used to create list slices as per following format:

seq = L[start:stop]



Question : 6
What do you understand by true copy of a list? How is it different from shallow copy?


Answer :

A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. In essence, a shallow copy is only one level deep. The copying process does not recurse and therefore won‘t create copies of the child objects themselves.

True Copy means you can create a copy of a list using New_list=My_list. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.



Question : 7
How are Tuples different from Lists when both are sequences?


Answer :

Tuples are similar to lists in many ways like indexing, slicing, and accessing individual values but they are different in the sense that –

Tuples are immutable while lists are mutable.

List can grow or shrink while tuples cannot.



Question : 8
Discuss the utility and significance of Tuples.


Answer :

Tuples are great for holding static data that you don't plan on modifying and changing a lot. Tuples are four to seven times faster than lists. This means for every list item manipulated, four to seven tuples could be manipulated within that time frame. This has huge advantages for scientific work, as this allows for speedy data reading.



Question : 9
How can you say that a tuple is an ordered list of objects?


Answer :

A tuple is an ordered list of objects. This is evidenced by the fact that the objects can be accessed through the use of an ordinal index amd for a given index, same element is returned everytime.



Question : 10
How are dictionaries different from Lists?


Answer :

The dictionary is similar to lists in the sense that it is also a collection of data-items but it is different from lists in the sense that lists are sequential collections(ordered) and dictionaries are non-sequential collections(unordered).

Elements in lists or tuples can be accessed by using indexes. But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list.



Question : 11
When are dictionaries more useful than lists?


Answer :

Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.



Question : 12
Discuss the utility and significance of Dictionaries.


Answer :

Dictionaries can be much more useful than lists when we wanted to store all our friends cell-phone numbers. We could create a list of pairs,(name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get-time consuming. Better would be if we could index the list by our friend‘s name. This is precisely what a dictionary does.



Question : 13
Why is a dictionary termed as an unordered collection of objects?


Answer :

But in dictionaries the values can be obtained using keys. By changing the sequence of key we can shuffle the order of elements of dictionary while this thing is not possible in list. In dictionaries there is no index. It uses its keys as index which can be rearranged. That‘s why a dictionary termed as an unordered collection of objects



Question : 14

What are strings ?



Answer :

A string is a sequence of characters. IT is basically just a bunch of words. It is the from of data used in programming for storing and manipulating text, such as words, names and sentences. We can write it in Python using sentences. We can write it in Python using single quotes, double quotes, or triple quotes.



Question : 15

Differentiate between physical line and logical line.



Answer :

A physical line is what we see when we write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.



Question : 16

What is the difference between (+) and (*) operators?



Answer :

The plus (+) sign is the string concatenation operator while the asterisk (*) is the repetition operator, We can concatenate strings with the "+" operator and create multiple concatenated copies of the string with the "*" operator. The use of + and * makes sense by analogy with equivalent to 4+4+4,mnwe expect 'Save' *3 to be the same as 'Save' + 'Save' + 'Save'.



Question : 17

What is the difference between Istrip() and rstrip() ?



Answer :

Istrip() removes characters (including white space characters) from the left, based on the argument passed whereas rstrip() removes characters (including whitespace characters) from the right, based on the argument passed. 



Question : 18

What do you mean by' strings are immutable ?



Answer :

Strings are immutable means that the contents of the string variable cannot be changed after it is created.



Question : 19

What is the function of slicing operation ?



Answer :

We can retrieve a slice (substring) of a string with a slice operation. The slicing operation is used by specifying the name of the sequence, followed by an optional pair of numbers separated by an optional pair of numbers separated by a colon, enclosed within square brackets.



Question : 20

What is the use of Docstrings ?



Answer :

Python has a feature called documentation strings, usually referred to by its short name, docstrings. Docstring is an important tool that we should make use of since it helps document the program better and makes it easier to understand.



Question : 21

How are empty strings represented in Python ?



Answer :

An empty string contains no characters and has length 0, represented by two quotation marks in Python .



Question : 22

"The quotes are not a  part of strings". Comment.



Answer :

The quotes are not a part of string. They only tell the computer where the string constant begins and ends. They can have any character or sign, including space in between them. 



Question : 23

Differentiate between ord() and chr() functions.



Answer :

ord() function returns the ASCII value of a character and requires single character only whereas chr() function takes ASCII value in integer from and returns the character corresponding to the ASCII value.



Question : 24

Write short note on subscript.



Answer :

A string is a sequence of characters. We can access the characters one at a time with the bracket operator. An individual character in a string is accessed using a subscript (index). The subscript should always be an integer (positive or negative)



Question : 25

 What do you mean by positive and negative indices ?



Answer :

In Python, indices that begin from 0 onwards indices, and the indices which begin from -1,-2,-3 in the backward direction are called negative indices. Positive subscript helps in accessing the strings from the beginning. Negative subscript helps in accessing the string from the end.



Question : 26

'String indices must be an integer'. Comment.



Answer :

We can se any expression, including variables and operators, as an integer. Otherwise, we might get an error. We can also use negative indices, which count backward, i.e., from the end of the string to the beginning.



Question : 27

 What do you mean by traversing a string ?



Answer :

Traversing a string means accessing all the elements of the string one after the other by using the subscript or index.



Question : 28

Write short note on membership operators.



Answer :

in and not in are membership operators. in operator returns true if a particular sub-string.
not in operator does the exact reverse of in. It returns true if a particular substring s not present in the specified string.



Question : 29

What is the significance of list ?



Answer :

A list is a collection of a number of values or variables in an ordered sequence. These values are called elements. The element can be any Python objects, including numbers, strings, functions, and other lists.



Question : 30

Lists are mutable. Comments ?



Answer :

Lists are mutable. This means that value of an item in a list can be modified with an assignment statement.



Question : 31

Why are Python Lists called dynamic arrays ?



Answer :

Lists are dynamic arrays. They are arrays in the sense that we can index items in a list (for example, mylist[3]), and we can select subranges (for example, mylist[2:4]).
They are dynamic in the sense that we can add and remove items after the list is created. 



Question : 32

How do list indices work in Python ?



Answer :

List indices work in the same way as string indices:
(a) Any integer expression can be used as an index.
(b) If we try read or write an element that does not exist, we get an IndexError.
(c) If an index has a negative value, it counts backward i.e., from the end of the list. 



Question : 33
Explain count() method with example.


Answer :

The count method counts the occurrences of an elements in a list. Fox example,
>>> [ 'to', 'be', 'or'. 'not','to','be'].count ('to')
2                                                                                                                                                                                                                                                                



Question : 34

What is index() method used for ?



Answer :

The index() method is used for searching lists to find the index of the first occurrence of a value. For example,
>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say',' in' ]
>>> knights.index('who')
4



Question : 35

What is aliasing ? Explain with an example.



Answer :

A circumstance where two or more variables refer to the same object is called aliasing. If variable a refers to an object and we assign b to a, then both variables refer to the same object.
For example,
>>> a = [ 1,3,5 ]
>>> b = a
>>> b is a 
true



Question : 36

What do you mean by sequence ?



Answer :

A sequence is an ordered collection of items, indexed by positive integers. It is combination of mutable and non-mutable data types. There types of sequence data types available in Python are strings, lists, and tuples.



Question : 37

What is indexing ?



Answer :

All elements in a sequence are numbered as from 0, 1, 2, and so on. We can access them individually with their respective number. This is called indexing. We use an index to fetch an elements. All sequences can be indexed in this way. When we use a negative index, Python counts from the right, that is, from the last element. The last element is at position -1. 



Question : 38

What is the default value for the first index if you omit the first index value in a slice ?



Answer :

The default value is zero (0).



Question : 39

What is the purpose of negative slice indices ?



Answer :

Negative indices can be used to count from the right end of the string.



Question : 40

Explain the functions of del statement, pop() and remove().



Answer :

The del statement can be used to remove an individual item, or to remove all items identified by a slice. The pop() method removes an individual item and returns it, while remove() searches for an item and returns it, while remove() searches for an item, and removes the first matching item from the list.



Question : 41

If two list are equivalent, is it necessary that they are identical also. Explain with an example.



Answer :

>>> a = [ 2, 4, 6 ]
>>> b = [2, 4, 6 ]
>>> a is b
False
Above two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necesarily identical.



Question : 42
Name three types of sequence objects.


Answer :

The types of sequence objects are string, tuple, and list.



Question : 43

Which item in the sequence is selected for an index value of - 1?



Answer :

The last item in the sequence is selected for an index value of -1



Question : 44

Just like C, C++, and Java, Python supports character type; True or False ?



Answer :

False. There is no character type in Python. Rather, a string items are characters.



Question : 45

How are lists formed ?



Answer :

Lists are formed by placing a commaseparated sequence of expression in square brackets



Question : 46

What are the characteristics of list ?



Answer :

A list is a sequence of  items stored as a single object. Characteristics of list are as follows:
(a) Items in a list can be accessed by indexing, and sublists can be extracted by slicing.
(b) Lists are mutable; individual items or entire slices can be replace through assignment statements.
(c) Lists can grow and shrink as needed. 



Question : 47

What is tuple ?



Answer :

Tuples are a sequence of values of any type, indexed by integers. They are immutable. They are enclosed in ().



Question : 48

A tuple in Python is immutable. Comment.



Answer :

A tuple in Python is immutable. This means, it cannot be modified as immutable object cannot be changed. Once created, it always has the same values.



Question : 49

What is the difference between objects and methods ?



Answer :

Strings,  lists, and tuples are objects, which means that they not only hold values, but they also have built-in behaviors called methods, that act on the values in the object.



Question : 50

Is an item assignment an a tuple possible ?



Answer :

No, an item assignment statement in tuple is not possible.



Question : 51

What is len() function used for in list and tuple?



Answer :

With lists and tuples, len() function returns the number of elements in the sequence, For example,
>>> len ( [ 'a' , 'b', 'c', 'd', ] )
4
>>> len ( ( 2, 4, 6, 8, 10, 12 ) )
6



Question : 52

What is the use of in operator ?



Answer :

The in operator cheeks whether the given element is contained in the tuple or not. For example,
>>> 4 in ( 2, 4, 6, 8 )
True
>>> 5 in ( 2, 4, 6, 8 )
False



Question : 53

Write short note on tuple assignment.



Answer :

An assignment to all the elements in a tuple is done using a single assignment statement. Tuple assignment occurs in parallel rather than in sequence, making it useful for swapping values.



Question : 54

How will you create tuple with zero element and 1 element ?



Answer :

Zero element: To create a tuple with zero elements, use only a pair of parentheses  "()". For example,
# Zero element tuple
x = ()

One element: For a tuple with one element, use a trailing comma.
# One-element tuple
y = ( "Sunday" ,)



Question : 55

Compare and contrast tuples and list.



Answer :

Tuples are very similar to lists, but tuples cannot be changed, i.e., no change in the contents of the tuple is allowed. A tuple can be viewed as a 'constant list'. While lists employ square brackets, tuples are written with standard parentheses or no parentheses.  



Question : 56

Can we update tuples?



Answer :

Like numbers and strings, tuples are immutable which means we cannot update them or change values of their elements.



Question : 57

What is the difference between list and tuple ?



Answer :

Lists are enclosed in brackets [ ], and their elements and size can be changed, whereas tuples are enclosed in parentheses ( ) and cannot be updated. Tuples can be thought of as "read only" lists.



Question : 58

Identity the following as mutable or immutable:
lists, numbers, strings, tuples and dictionaries.



Answer :

Mutable : lists, dictionaries
Immutable : numbers, strings, tuples



Question : 59

How will you create an empty tuple ?



Answer :

We can create an empty tuple using built-in function tuple() as follows:
>>> t = tuple ()
>>> print t
()



Question : 60

What is dictionary?



Answer :

A dictionary is another container type that can store any number of Python objects, including other container types. It is mutable. It consists of pairs (called items) of keys and their corresponding values. It is also known as associative array or hash table.



Question : 61

Compare and contrast dictionaries (dicts) with other Python data types.



Answer :

(a) Dictionaries are a container type that store data, like lists and tuples.
(b) Dictionaries are a mapping data type indexed by text (keys). The dictionary's elements (the items it contains) are key:value pairs. In contrast, lists and tuples store data by using numeric indexes (they are sequence data types) and support indexing and slicing.
(c) Dictionaries are mutable. That means, a dictionary can be modified in place; we do not have to create a copy of it to modify it (as we do with strings and tuples ). However, a dict's keys must be immutable.



Question : 62

What are the advantages of hash ?



Answer :

Hashes are used for space-efficient storage, for security and cryptography, and so on. Another benefit of hashing is that after the hash value is computed, keys can be looked directly; there's no need for the computer to search through a whole list of keys. In Python, This feature makes dictionaries very fast.



Question : 63

Does Python store dictionary elements in any particular order?



Answer :

No, python does not store dictionary elements in any particular order. If we enter elements in one order, they may be stored in another (essentially random) order inside Python. For example,
>>> D1 = { ' sleep' : " All night ", 'work' : "All day"}
>>> D1
{ 'work' : 'All day', 'sleep' : 'All night' }



Question : 64

What is a mapping ?



Answer :

A mapping is a structure in which values are stored and retrieved according to a key. This data type is unordered and mutable. However keys of a dictionary must be unique and immutable. This is often called a dictionary, as it behaves similar to a common dictionary.



Question : 65

What is another name for mapping ?



Answer :

A dictionary.



Question : 66

What are the characteristics of a Python dictionary?



Answer :

The characteristics of a Python dictionary are as follows:
(a) A dictionary is an unordered collection of objects.
(b) Values are accessed using a key rather than an ordinal numeric index.
(c) The dictionary can shrink or grow as needed.
(d) It can be nested.
(e) The contents of dictionaries can be modified.



Question : 67

A dictionary is an mutable object. Comment.



Answer :

A dictionary is mutable as its existing items can be modified, new items can be added to it, and existing items can be deleted from it.



Question : 68

A dictionary is an unordered collection of objects. Comment.



Answer :

The items in a dictionary are not maintained in any specific order, and the dictionary can contain references to any type of objects.



Question : 69

Can sequence operations, such as slicing and concatenation, be applied to dictionaries?



Answer :

No, the dictionary is not a sequence. Since it is not maintained in any specific order, operations that depend on the specific order cannot be used. 



Question : 70

Write the syntax of a dictionary.



Answer :

A dictionary consists of one or more key:value pairs, separated by commas, and enclosed in a pair of curly braces. It can be empty also, i.e., having no items.



Question : 71

Can you remove key:value pairs from a dictionary. If so, how ?



Answer :

We can use del statement to remove an existing key:value pair from a dictionary.



Question : 72

What do you mean by traversing a dictionary ?



Answer :

Traversing a dictionary means visiting each element of the dictionary to display its values on the screen.



Question : 73

Can you merge two dictionaries ? If so, how?



Answer :

Two dictionaries can be merged into one by using update() method. It merges the keys and values of one dictionary with that of another and overwrites values of the same key.



Question : 74

Discuss the properties of Dictionary Keys.



Answer :

There are few properties which should be considered while using dictionary keys:
(a) More than one entry per key is not allowed ( no duplicate key is allowed ).
(b) The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples, or strings.
(c) Dictionary keys are case sensitive. Same key name but with the different case are treated as different keys in Python dictionaries. 



Question : 75

What do the keys(), values() and items() functions do ?



Answer :

keys(): Returns a list of the keys.
values(): Returns a list of the values.
items(): Returns a list of tuples (key,value)
representing the key:value pairs.



Question : 76

Write different capabilities of dictionary.



Answer :

A dictionary has the following capabilities:
(a) Ability to iterate over keys or values or key-value pairs.
(b) Ability to add key-value pairs dynamically.
(c) Ability to look for a value by key.



Question : 77

Write difference between lists and dictionaries.



Answer :

The difference between lists and dictionaries are:
(a) In dictionary, index value can be of any data type and is called key, but in list index value is an integer.
(b) No sequence operation such as slicing and concatenation be applied to dictionaries as dictionary is not a sequence. Since it is not maintained in any specific order, operation that depends on a specific order can not be used where as slicing and concatenation are applied on lists.
(c) List are sequential collections (ordered) and dictionaries are non-sequential collections (unordered).



Question : 78

What is the purpose of a header file in a Python program?



Answer :

A header file provides a centralized location for the declaration of all extern variables, function prototypes, etc. Files that must use or define a variable or a function, include header file(s). By using header files, two main safeguards are provided.



Question : 79

What is function ?



Answer :

A named sequence of statements that performs some useful operation. functions may or may not take arguments and may or may not produce a result.



Question : 80

What are the advantages of using functions.



Answer :

Functions let us write code only once.
Functions hide unnecessary complexity from the user.
Functions make our code easier to understand.
Functions help us organize our program logically.



Question : 81

What is function definition ?



Answer :

A statement that creates a new function, specifying its name, parameters, and the statements it executes is called function definition.



Question : 82

Write a short note on built-in function.



Answer :

Built-in functions are then functions that are built into Python and can be accessed by programmer any time without importing any module (file) such functions are input(), int(), float(), type(), help() etc. 



Question : 83

How is built-in function accessed ?



Answer :

Built-in function is accessed simply by writing the function name, followed by an optional list of arguments that represent information being passed to the function.



Question : 84

How will you import all functions in the math module ?



Answer :

from math import *



Question : 85

What is difference between cell() and floor() functions?



Answer :

The function ceil() returns the smallest whole number greater than or equal to x . The floor() function returns the largest whole number less than or equal to x .



Question : 86

What is Python module ?



Answer :

A module is a file that contains a collection of related functions and other definitions. We can make a mudule available to another program by importing it.



Question : 87

How will you import specific names only within a module?



Answer :

We can import specific names only within a module, without importing the whole module, by using the  from  <module>  import  <name>  statement.



Question : 88

Write short note on user defined function.



Answer :

A part from the library functions that are in built in Python, users can also define functions to do a task relevant to their programs. Such functions are called user-defined functions. These functions should be codified by the user, so that any call to the function can refer to it.



Question : 89

What is difference between pow() and **?



Answer :

Both pow() and the double star (** ) operator perform exponentiation. ** is an operator and pow() is a built-in function.



Question : 90

What do you mean by Regular expressions ?



Answer :

Regular expressions called regexes for short, are descriptions for a pattern of text. For example, a\ d in a regex stands for a digit character. They allow us to specify a pattern of text to search for. 



Question : 91

What is a metacharacter?



Answer :

Each character in a Python Regex is either a metacharacter or a regular character. A metacharacters are characters with a special meaning, while a regular character matches itself.



Question : 92

How match() function is different from search() function ?



Answer :

The match() function returns a match object if the text matches the pattern. Otherwise it returns None. The match() functions looks for a pattern at the beginning of a string. The search() function checks for a match anywhere in the string. If there is more than one match, only the first occurrence of the match will be returned.



Question : 93

What do you mean by greedy match and non greedy match ?



Answer :

When a special character matches as much of the search sequence (string) as possible, it is said to be a greedy match. Non greedy matches the smallest number of repetitions.



Question : 94

Differentiate between max() and min() functions ?



Answer :

Python built-in function max() returns the largest of its parameters. Python built-in function min() returns the smallest of its parameters.



Question : 95

Write a short note on random module.



Answer :

The random module contains function related to generating random numbers and producing random results. Random numbers have many applications in science and computer programming, especially when there are significant uncertainties in a phenomenon of interest.



Question : 96

Write a short note on randint().



Answer :

If we wanted a random integer, we can use the randint() function. Randint accepts two parameters: a lowest and a highest number, and returns an integer between lowest and highest (including both).



Question : 97

Observe the following Python function and write the name(s) of the module(s) to which they belong:
a. uniform()  b. findall()



Answer :

a. random b. re



Question : 98

What is file Pointer ?



Answer :

When a file is opened using method, the operating system associates a pointer that points to a character in the file. The file pointer determines from where the read and write operation will take place. Initially, the file pointer points at the start of the file.



Question : 99

Discuss various modes to open a file.



Answer :

'r' : This mode indicates that file will be open for reading only.
'w' : This mode indicates that file will be open for writing only. If file, does not exists, it will create a new one.
'a' : This mode indicates that the output of that program will be append to the previous output of the file.
'r+' : This mode indicates that file will be open for both reading and writing.



Question : 100

Write short note on binary mode of opening a file.



Answer :

Binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.



Question : 101

Differentiate between read() and readline().



Answer :

read() function reads the entire file and returns a string.
readline() function reads lines from that file and returns as a string. It fetches the line n, if it is being called  nth time.

     

                                                                                                                       



Question : 102

Write function of a+ mode.



Answer :

The a+ mode opens a file for both appending and reading. The file pointer is at the end of the file if the exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.



Question : 103

What are different ways to read from a file ?



Answer :

To read a file Python provides different reading methods. There are three ways to read from a file.
read ([n])
readline ([n])
readlines ()
where n is the number of bytes to be read.
The read() method just outputs the entire file if number of bytes are not given in the argument.
The readline(n) outputs at most n bytes of a single line of a file. It does not read more than one line. The readlines() returns a list where each element is single line of that file.



Question : 104

What are command line arguments?



Answer :

Command line arguments are flags given to a program / script at runtime. They contain additional information for our program so that it can execute. 



Question : 105

Why do we use command line arguments ?



Answer :

Command line arguments give additional information to a program at runtime. This allows us to give our program different input without changing the code.



Question : 106

What is the use of getopt method ?



Answer :

This method parses command line options and parameter list.



Question : 107

What are the different file processing modes supported by Python ?



Answer :

Python provides different modes to open files. The read-only, write-only, read-write and append mode. 'r' is used to open a file in read-only mode, 'w' is used to open a file in write-only mode, 'rw' is used to open in reading and write mode, 'a' is used to open a file in append mode. If the mode is not specified, by default file opens in read-only mode. 



Question : 108

What is pickling and unpickling in Python ?



Answer :

Pickling is a process in which a pickle module accepts any Python objects, converts it into a string representation and dumps it into a file by using dump() function.
Unpickling is a process of retrieving original Python object from the stored string representation for use.



Question : 109

What is the use of offset ?



Answer :

The offset refers to the byte count which determines the position relative to which the offset will move the file pointer. In other words offset is used to calculate the position of fileobject in the file in bytes. Offset is added to from_what ( reference point) to get the position.



Question : 110

Write a statement in Python to open a text file DATA.TXT so that new contents can be written in it.



Answer :

file=   open("DATA.TXT","w+") OR         file=   open("DATA.TXT","w+")



Question : 111

Differentiate between readlines() and readline() functions.



Answer :

Python's readlines() function reads all the lines in a file, while readline() only reads  one line at a time, which may help save memory.



Question : 112

Name two functions which allow us to access a file in a non-sequential or random mode.



Answer :

seek() and tell()



Question : 113

Name the file which is stored in human readable form and can also be created using any text editor.



Answer :

Text files are stored in human readable form and also be created using any text editor.



Question : 114

What is the use of seek() and tell() methods?



Answer :

To access the contents of the randomly - seek and tell methods are used. tell() method returns an integer giving the current position of object in the file. The integer returned specifies the number of bytes from the beginning of the file till the current position of file object.



Question : 115

What is the use of close() method ?



Answer :

The close() will be used to close the file object, once we have finished working on it. The method will free up all the system resources used by the file, this means that once file is closed, we will not be able to use the file object any more.



Question : 116

What do you understand by module and package ?



Answer :

A module is a file containing Python codes-including statements, variables, functions and classes. It shall be saved with file extension of ".py". On the other hand a Package is simply a directory of Python modules.



Question : 117

What do you mean by LEGB ?



Answer :

The order for name resolution (for names inside a function) is: local, enclosing function for nested def, global, and then the built-in namespaces (i,e., LEGB).
L: Local namespace which is specific to the current function.
E: for nested function, the Enclosing function's namespace.
G: Global namespace for the current module.
b: Built-in namespace for all the modules.                                                                           



Question : 118

What is namespace in Python ?



Answer :

A namespace is a naming system used to make sure that names are unique to avoid naming conflicts



Question : 119

Name any two commonly used build-in modules.



Answer :

math and random



Question : 120

What do you mean by Global variable ?



Answer :

Global variable means that it is accessible from anywhere in our script, including from within a function. It is usually defined at the top of the script or outside of the function.



Question : 121

What do you mean by Built-in ?



Answer :

Built-in means the function and variables that are already defined in Python.



Question : 122

What do you understand by following import statement :
from x import a, b, c



Answer :

It import the module X, and creates references in the current namespace to the given objects.
Or in other words, we can now use a, b and c in our program.



Question : 123

What do you mean by reloading module ?



Answer :

In reloading module, instead of creating a new module object, the existing module is re-used.
By re-using the same object, existing references to the module are preserved even if class or function definitions are modified by the reload.



Question : 124

How will you import all the attributes from a module ?



Answer :

We can also import all the attributes from a module by using *. The syntax is given below:
from  <module>  import *
For example, from math import *



Question : 125

Write short note on from-import statement.



Answer :

Instead of importing the whole module into the namespace, Python provides the flexibility to import only the specific attributes of a module. This can be done by using from import statement.
The syntax to use the from-import statement is given below:
from <  module-name>  import  <name  1>,  <name 2>.., <name n>



Question : 126

What is numpy ?



Answer :

NumPy ("Numerical Python" or "Numeric Python") is an open source module of Python that offers functions and routines for fast mathematical computation on array and matrices.



Question : 127

Name the module you will import to use numpy ?



Answer :

In order to use Numpy, we must import in your module by using a statement like:
import numpy as np



Question : 128

What is slicing ?



Answer :

Slicing in the NumPy array is the way to extract a range of elements from an array, Slicing in the array is performed in the same way as it is performed in the Python list.



Question : 129

What do you mean by Axes in numpy ?



Answer :

Numpy refers to the dimensions of its arrays as axes. Axes are always numbered 0 onwards for ndarrays.



Question : 130

What do you mean by Rank in numpy ?



Answer :

The number of axes in an ndarray is called its rank.



Question : 131

Write short note on slicing.



Answer :

Just like lists in Python, NumPy arrays can be sliced. As rrays can be multidimensional, you need to specify a slice for each dimension of the array. Slicing can be done over multiple dimensions. It cannot be used to expand the size of an array (unlike lists).



Question : 132

What is the purpose of negative index values in NumPy ?



Answer :

NumPy also supports negative index values. Using a negative index allows us to retrieve or reference locations starting from the end of the array.



Question : 133

Define Array and NumPy array.



Answer :

Array : Group or collection of similar type of elements. For example, scores of players in a cricket match, marks of students in a class etc.
NumPy array: A grid contains value of same type (homogeneous elements).



Question : 134

Explain membership operator in with example.



Answer :

Membership operator in returns true if a character exists in the given string, and false other-wise. For example,
>>>  str = "work Hard"
>>> 'w'  in str
True
>>> 'work' in str
True
>>> 'work' in str
False  # because w of work is in small case
>>> 'we' in str
False



CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online Exam Quiz O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Best Website and Software Company in Allahabad Website development Company in Allahabad