Python Interview Questions on Data Types and Their in-built Functions

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Data Types and Their in-built Functions

Data types in Python

Numbers: int, float, and complex
List: Ordered sequence of items
tuple: Ordered sequence of items similar to list but is immutable
Strings: Sequence of characters
Set: an unordered collection of unique items
Dictionary: an unordered collection of key-value pair

Question 1.
Differentiate between mutable and immutable objects?
Answer:

Mutable Objects Immutable Objects
Can change their state or contents Cannot change their state or contents
Type: list, diet, set Inbuilt types: int, float, bool, string, Unicode, tuple
Easy to change Quick to access but making changes require the creation of a copy
Customized container like types are mostly mutable Primitive like data types are immutable
  • Mutable objects are recommended when one has the requirement to change the size or content of the object
  • The exception to immutability: tup1es are immutable but may contain elements that are mutable

Question 2.
What is Variable in Python?
Answer:
Variables in Python are reserved memory locations that store values. Whenever a variable is created, some space is reserved in the memory. Based on the data type of a variable, the interpreter will allocate memory and decide what should be stored in the memory.

>>> a = 9 #assign value to a
>>> type(a) #check type of variable a
<class 'int'>
>>>

Question 3.
How can we assign the same value to multiple variables in one single go?
Answer:
The same value can be assigned to multiple variables in one single go as shown in the following code:

>>> a = b = c = "Hello World ! ! ! "
>>> a
' Hello World ! ! ! '
>>> b
' Hello World ! ! ! '
>>> c
' Hello World ! ! ! '
>>>

Numbers
Types of numbers supported are as follows:

  1. Signed integers int: these can be +ve or -ve and do not have any decimal point
  2. Long integers long: these are integers of unlimited size followed by capital or lowercase ‘L’
  3. Float: are real numbers with decimal points
  4. Complex numbers: have real and imaginary parts

Question 4.
What are the methods available for the conversion of numbers from one type to another?
Answer:
The following functions are available to convert numbers from one form to another.

# convert to integer
a = 87.8
print("a = ", a)
print ("****************")
#After conversion to integer
print("After conversion to integer value of a will be a = ", int(a))
print("*****************")
# convert to float
a = 87
print("a = ", a)
print("*****************")
#After conversion to float
print ("After conversion to float value of a will
be a = ", float (a) )
print("*****************")
# convert to complex
a = 87
print("a = ",a)
#After conversion to complex
print("After conversion to complex value of a will be = ", complex(a))
print("*****************")

Output

a = 87.8
*****************
After conversion to integer, the value of a will be a = 87
*****************
a = 87
*****************
After conversion to float value of a will be a = 87.0
a = 87
After conversion to complex value of a will be =
(87 + 0j)
*****************
>>>

Question 5.
What are the mathematical functions defined in Python to work with numbers?
Answer:
Mathematical functions are defined in the

import math
#ceiling value
a = -52.3
print ("math ceil for ",a, " is : " ceil(a))
print ("********************")
#exponential value
a = 2
print("exponential value for ", a , exp(2))
print ("********************")
#absolute value of x
a = -98.4
print ("absolute value of ",a," is: ", abs(a) )
print("********************")
#floor values
a = -98.4
print ("floor value for ",a," is: " print )
# log(x)
a = 10
print ("log value for ",a," is : ", math . floor (a))
print ("********************")
# log10(x)
a = 56
print ("log to the base 10 for ",a," is : ", math . log10(a))
print ("********************")
# to the power of
a = 2
b = 3
print (a," to the power of ",b," is : " , pow(2,3))
print ("********************")
# square root
a = 2
print("sqaure root")
print ("Square root of ",a," is : " , math . sqrt(25))
print("********************")

math module. You will have to import this module in order to work with these functions.

Output

math ceil for -52.3 is: -52
********************
exponential value for 2 is: 7.38905609893065
********************
the absolute value of -98.4 is: 98.4
********************
floor value for -98.4 is: -99
********************
log value for 10 is: 2.302585092994046
********************
log to the base 10 for 56 is :
1.7481880270062005
********************
2 to the power of 3 is: 8.0
********************
square root
The square root of 2 is: 5.0
********************

Question 6.
What are the functions available to work with random numbers?
Answer:
To work with random numbers you will have to import a random module. The following functions can be used:

import random
#Random choice
print (" Working with Random Choice")
seq=[8,3,5,2,1,90,45,23,12,54]
print ("select randomly from ", seq," : ", random, choice(seq))
print("*******************")
#randomly select f?om a range
print ("randomly generate a number between 1 and 10 : ", random.randrange(1, 10))
print("*******************")
#random( )
print ("randomly display a float value between 0 and 1 : ",random.random())
print("* * * * * *")
#shuffle elements of a list or a tup1e
seq= [1,32,14,65,6,75]
print ("shuffle ",seq,"to produce ", random,
shuffle (seq) )
#uniform function to generate a random float number between two numbers
print ("randomly display a float value between 65 and 71 : ", random.uniform(65,71))

Output

Working with Random Choice
select randomly from [8, 3, 5, 2, 1, 90, 45, 23, 12, 54] : 2
*******************
randomly generate a number between 1 and 10: 8
*******************
randomly display a float value between 0 and 1: 0.3339711273144338
* * * * * *
shuffle [1, 32, 14, 75, 65, 6] to produce: None
randomly display a float value between 65 and 71 :
65.9247420528493

Question 7.
What are the trigonometric functions defined in the math module?
Answer:
Some of the trigonometric functions defined in the

import math
# calculate arc tangent in radians
print ("atan(0) : ",math.atan(0))
print ("**************")
# cosine of x
print ("cos (90) : ", math.cos(0))
print("**************")
# calculate hypotenuse
print ("hypot(3,6) : ",math.hypot(3,6))
print ("**************")
# calculates sine of x
print ("sin(O) : ", math.sin(0))
print ("**************")
# calculates tangent of x
print ("tan(0) : ", math.tan(0))
print("**************")
# converts radians to degree
print ("degrees(0.45) : ", math.degrees(0.45))
print("**************")
# converts degrees to radians
print ("radians(0) : ", math.radians(0))

math module is as follows:

Question 8.
What are number data types in Python?
Answer:
Number data types are the one which is used to store numeric values such as:

  1. integer
  2. long
  3. float
  4. complex

Whenever you assign a number to a variable it becomes a numeric data type.

>>> a = 1
>>> b = -1
>>> c = 1 . 1
>>> type (a)
<class 'int'>
>>> type (b)
<class 'int'>
>>> type (c)
<class 'float'>

Question 9.
How will you convert float value 12.6 to integer value?
Answer:
Float value can be converted to an integer value by calling int() function.

>>> a = 12.6
>>> type(a)
<class 'float' >
>>> int(a)
12
>>>

Question 10.
How can we delete a reference to a variable?
Answer:
You can delete a reference to an object using the del keyword.

>>> a=5
>>> a 5
>>> del a
>>> a
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a
NameError: name 'a' is not defined
>>>

Question 11.
How will you convert real numbers to complex numbers?
Answer:
Real numbers can be converted to complex numbers as shown in the following code:

>>> a = 7
>>> b = -8
>>> x = complex(a,b)

>>> x.real
7.0
>>> x.imag
-8.0
>>>

Keywords, Identifiers, and Variables

Keywords

  • Keywords are also known as reserved words.
  • These words cannot be used as a name for any variable, class, or function.
  • Keywords are all in lower case letters.
  • Keywords form vocabulary in Python.
  • The total number of keywords in Python is 33.
  • Type help() in Python shell, a help> prompt will appear. Type keywords. This would display all the keywords for you. The list of keywords is highlighted for you.

Welcome to Python 3.7’s help utility?

If this is your first time using Python, you should definitely check: cut the tutorial on the Internet at https://docs.python.orgy 3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type “quit”.

To get a list of available modules, keywords, symbols, or topics, type “modules”, “keywords”, “symbols”, or “topics”. Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such 33 “spam”, type “modules spam”.

help> keywords

Here is a list of the python keywords, Enter any keyword to get more help.

Python Interview Questions on Data Types and Their in-built Functions chapter 2 img 1

help

Identifiers

  • Python Identifier is a name given to a variable, function, or class.
  • As the name suggests identifiers provide an identity to a variable, function, or class.
  • An identifier name can start with upper or lower case letters or an underscore followed by letters and digits.
  • An identifier name cannot start with a digit.
  • An identifier name can only contain letters, digits, and an underscore.
  • special characters such as @,%,! , #,$,’.’ cannot be a part of the identifier name.
  • As per naming convention, generally, the class name starts with a capital letter, and the rest of the identifiers in a program should start with lower case letters.
  • If an identifier starts with a single underscore then it is private and two leading underscores in front of an identifier’s name indicate that it is strongly private.
  • Avoid using an underscore as a leading or trailing character in an identifier because this notation is being followed for Python built-in types.
  • If an identifier also has two trailing underscores then it is a language-defined special name.
  • Though it is said that a Python identifier can be of unlimited length but having a name of more than 79 characters is a violation of the PEP-8 standard which asks to limit all lines to a maximum of 79 characters.
    You can check if an identifier is valid or not by calling iskeywords( ) function as shown in the following code:
>>> import keyword
>>> keyword.iskeyword("if")
True
>>> keyword.iskeyword("only")
False

Variables

  • Variables are nothing but a label to a memory location that holds a value.
  • As the name suggests, the value of a variable can change.
  • You need not declare a variable in Python but they must be initialized before use E.g, counter =0.
  • When we pass an instruction counter=0, it creates an object and a value 0 is assigned to it. If the counter variable already exists then it will be assigned a new value 0 and if it does not exist then it will get created.
  • By assigning a value we establish an association between a variable and an object.
  • counter=0 means that the variable counter refers to a value of ‘0’ in memory. If a new value is assigned to the counter then that means the

variable now refers to a new memory chunk and the old value was garbage collected.

>>> counter = 0
>>> id(counter)
140720960549680
>>> counter =10
>>> id(counter)
140720960550000
>>>

Question 12.
What are tokens?
Answer:
Tokens are the smallest units of the program in Python. There are four types of tokens in Python:

  • Keywords
  • Identifiers
  • Literals
  • Operators

Question 13.
What are constants?
Answer:
Constants (literals) are values that do not change while executing a program.

Question 14.
What would be the output for 2*4**2? Explain.
Answer:
The precedence of** is higher than the precedence of*. Thus, 4**2 will be computed first. The output value is 32 because 4**2 = 16 and 2*16 = 32.

Question 15.
What would be the output for the following expression:

print('{0:.4}'.format(7.0 / 3))

Answer:
2.333

Question 16.
What would be the output for the following expression?

print('(0:.4%}'.format(1 / 3))

Answer:
33.3333%

Question 17.
What would be the value of the following expressions?

  1. ~5
  2. ~~5
  3. ~~~5

Answer:
~x = -(x+1). Therefore the output for the given expressions would be as follows:

  1. -6
  2. 5
  3. -6

We will now have a look at the three most important sequence types in Python. All three represent a collection of values that are placed in order. These three types are as follows:

  1. String: immutable sequence of text characters. There is no special class for a single character in Python. A character can be considered as a String of text having a length of 1.
  2. List: Lists are very widely used in Python programming and a list represents a sequence of arbitrary objects. The list is mutable.
  3. tuple: tup1e is more or less like a list but it is immutable.

Strings

  • The sequence of characters.
  • Once defined cannot be changed or updated hence strings are immutable.
  • Methods such as replace( ), join( ), etc. can be used to modify a string variable. However, when we use these methods, the original string is not modified instead Python creates a copy of the string which is modified and returned.

Question 18.
How can String literals be defined?
Answer:
Strings can be created with single/double/triple quotes.

>>> a = "Hello World"
>>> b = 'Hi'
>>> type(a)
<class 'str'>
>>> type(b)
<class 'str' >
>>>
>>> c = """Once upon a time in a land far far away there lived a king"""
>>> type(c)
<class 'str'>
>>>

Question 19.
How can we perform concatenation of Strings?
Answer:
Concatenation of Strings can be performed using the following techniques:

1. + operator

>>> string1 = "Welcome"
>>> string2 = " to the world of Python!!!"
>>> string3 = string1 + string2
>>> string3
'Welcome to the world of Python!!!'
>>>

2. Join ( ) function

The join( ) function is used to return a string that has string elements joined by a separator. The syntax for using join( ) function, string_name.j oin(sequence)

>>> string1 = "-"
>>> sequence = ( "1","2","3","4")
>>> print(string1.joint(sequence))
1-2-3-4
>>>

3. % operator

>>> string1 = "HI"
>>> string2 = "THERE"
>>> string3 = "%s %s" %(string1, string2)
>>> string3 ,
'HI THERE'
>>>

4. format( ) function

>>> string1 = "HI"
>>> string2 ="THERE"
>>> string3 = "{ } { }" . format (string1, string2)
>>> string3
'HI THERE'
>>>

5. f-string

>>> string1 ="HI"
>>> string2 = "THREE"
>>> string3 = f ' { string1} {string2} '
>>> string3
'HI THERE'
>>>

Question 20.
How can you repeat strings in Python?
Answer:
Strings can be repeated either using the multiplication sign or by using for loop.

  • operator for repeating strings
>>> string1 = "Happy Birthday!!!"
>>> string1*3
'Happy Birthday!!!Happy Birthday!!!Happy Birthday!!!' *
>>>
  • for loop for string repetition
for x in range (0,3)

>>> for x in range(0,3):
print("HAPPY BIRTHDAY! ! !")

Question 21.
What would be the output for the following lines of code?

>>> string1 = "HAPPY "
>>> string2 = "BIRTHDAY!!!"
>>> (string1 + string2)*3

Answer:

'HAPPY BIRTHDAY!!!HAPPY BIRTHDAY!!!HAPPY BIRTHDAY!!!'

Question 22.
What is the simplest way of unpacking single characters from string “HAPPY”?
Answer:
This can be done as shown in the following code:

>>> string1 = "HAPPY"
>>> a,b,c,d,e = string1
>>> a
'H'
>>> b
'A'
>>> c
'P'
>>> d
'P'
>>> e
'Y'
>>>

Question 23.
Look at the following piece of code:

>>> string1 = "HAPPY"
>>> a,b = string1

What would be the outcome for this?
Answer:
This code will generate an error stating too many values to unpack because the number of variables does not match the number of characters in the strings.

Question 24.
How can you access the fourth character of the string “HAPPY”?
Answer:
You can access any character of a string by using Python’s array-like indexing syntax. The first item has an index of 0. Therefore, the index of the fourth item will be 3.

>>> string1 = "HAPPY"
>>> string1[3]
'P'

Question 25.
If you want to start counting the characters of the string from the rightmost end, what index value will you use (assuming that you don’t know the length of the string)?
Answer:
If the length of the string is not known we can still access the rightmost character of the string using the index of -1.

>>> string1 = "Hello World!!!"
>>> string1[-1]
' ! '
>>>

Question 26.
By mistake, the programmer has created string string1 having the value “HAPPU”. He wants to change the value of the last character. How can that be done?
Answer:
Strings are immutable which means that once they are created they cannot be modified. If you try to modify the string it will generate an error.

>>> string1 = "HAPPU"
>>> string1 [-1] = "Y"
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
string1[-1] = "Y”
TypeError: fstr* object does not support item assignment

However, there is a way out for this problem. We can use the replace( ) function.

>>> string1 = "HAPPU"
>>> string1.replace('U'Y')
'HAPPY'

Here, in the case of replace ( ) function, a new string is created and the value is reassigned to string1. So, string1 is not modified but is actually replaced.

Question 27.
Which character of the string will exist at index -2?
Answer:
Index of -2 will provide second last character of the string:

>>> string1 = "HAPPY"
>>> string1 [-1]
' Y'
>>> string1[-2]
'P'
>>>

Question 28.
>>> str1 = “\t\tHi\n”
>>> print(str1 .strip ( ))
What will be the output?
Answer:
Hi

Question 29.
Explain slicing in strings.
Answer:
Python allows you to extract a chunk of characters from a string if you know the position and size. All we need to do is to specify the start and endpoint. The following example shows how this can be done. In this case, we try to retrieve a chunk of the string starting at index 4 and ending at index 7. The character at index 7 is not included.

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1 [4:7]
'Y-B'
>>>

If in the above example you omit the first index, then the default value of 0 is considered and the slicing of text chunks starts from the beginning of the string.

>>> String1 = "HAPPY-BIRTHDAY! ! ! "
>>> string1 [:7]
'HAPPY-B'
>>>

Same way if you don’t mention the second index then the chunk will be taken from the starting position till the end of the string.

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1 [4:]
'Y-BIRTHDAY!!!'

Value of string1 [:n]+string1[n:] will always be the same string.

>>> string1 [:4]+ string1 [4:]
'HAPPY-BIRTHDAY!!!'

The negative index can also be used with slicing but in that case, the counting would begin from the end.

>>>string1 = "HAPPY-BIRTHDAY ! ! !"
>>> string1[-5:-1]
'AY!!' ! ”
>>>

You can also provide three index values:

>>> string1 [1:7:2]
'AP- '
>>> string1 [1: 9 : 3]
'AYI'
>>>

Here, the first index is the starting point, the second index is the ending point and the character is not included and the third index is the stride or how many characters you would skip before retrieving the next character.

Question 30.
What would be the output for the following code?

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1[-1:-9:-2]
Answer:
‘!!AH’

Question 31.
How does the split( ) function work with strings?
Answer:
We can retrieve a chunk of string based on the delimiters that we provide. The split( ) operation returns the substrings without the delimiters.

Example

>>> string1 = "Happy Birthday"
>>> string1.split ( )
['Happy', 'Birthday' ]

Example

>>> time_string = "17:06:56"
>>> hr_str,min_str,sec_str = time_string. split (":")
>>> hr_str
'17'
>>> min_str
'06'
>>> sec_str
'56'
>>>

You can also specify, how many times you want to split the string.

>>> date_string = "MM-DD-YYYY"
>>> date_string.split("-" , 1)
['MM', 'DD-YYYY']
>>>

In case you want Python to look for delimiters from the end and then split the string then you can use the rsplit( ) method.

>>> date_string = "MM-DD-YYYY"
>>> date_string.split("-" , 1)
['MM-DD', 'YYYY']
>>>

Question 32.
What is the difference between the splif() and partltion( ) function?
Answer:
The result of a partition function is a tup1e and it retains the delimiter.

>>> date_string = "MM-DD-YYYY"
>>> date_string.partition("-" , 1)
('MM', ' - ' , 'DD-YYYY')

The partition ( ) function on the other hand looks for the delimiter from the other end.

>>> date_string = "MM-DD-YYYY"
>>> date_string.rpartition("-")
('MM-DD', '-', 'YYYY')
>>>

Question 33.
Name the important escape sequence in Python.
Answer:
Some of the important escape sequences in Python are as follows:

  • \\: Backslash
  • \’: Single quote
  • \”: Double quote •
  • \f: ASCII form feed
  • \n: ASCII linefeed
  • \t: ASCII tab
  • \v: Vertical tab

String Methods

capitalize ( )
Will return a string that has first alphabet capital and the rest are in lower case, ‘

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.capitalize ( )
'Happy birthday'
>>>

casefold( )

Removes case distinction in string. Often used for caseless matching. ‘

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.casefold()
'happy birthday'
>>>

centre( )

The function takes two arguments: (1) length of the string with padded characters (2) padding character (this parameter is optional)

>>> string1 = "HAPPY BIRTHDAY"
>>> new_string = string1.center(24)
>>> print("Centered String: ", new_string)
Centered String: HAPPY BIRTHDAY
> >>

count( )

Counts the number of times a substring repeats itself in the string.
>>> string1 = "HAPPY BIRTHDAY"
>>> string1.count("P")
2
>>>

You can also provide the start index and ending index within the string where the search ends.

encode( )

Allows you to encode Unicode strings to encodings supported by python.

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.encode( )
b'HAPPY BIRTHDAY'

By default, python uses utf-8 encoding.
It can take two parameters:
encoding – type a string has to be encoded to and
error- response when encoding fails

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.endswith('Y')
True
>>> string1.endswith('i')
False

endswith( )

It returns true if a string ends with the substring provided else it will return false.

>>> string1 = "to be or not to be"
>>> string1.endswith("not to be")
True
>>>

find( )

Get the index of the first occurrence of a substring in the given string.

>>> string1 = "to be or not to be"
>>> string1 .find ('be' )
3
>>>

format( )

The format function allows you to substitute multiple values in a string. With the help of positional formatting, we can insert values within a string. The string must contain {} braces, these braces work as a placeholder. This is where the values will be inserted. The format) the function will insert the values.

Example

 >>> print("Happy Birthday { }".format("Alex"))
Happy Birthday Alex

Example

>>> print("Happy Birthday { }, have a { } day!!", format("Alex","Great"))
Happy Birthday Alex, have a Great day ! !
>>>

 

Values that exist in the format( ) are tup1e data types. A value can be called by referring to its index value.

Example

>>> print("Happy Birthday {0}, have a {l} day!!", format("Alex","Great"))
Happy Birthday Alex, have a Great day!!
>>>

 

More types of data can be added to the code using {index: conversion} format where the index is the index number of the argument and conversion is the conversion code of data type.

s- string
d- decimal
f- float
c- character
b- binary
o- octal
x- hexadecimal with lower case letters after 9
X-hexadecimal with upper case letters after 9
e-exponent

Example

>>> print("I scored {0:.2f}% in my exams" . format(86))
I scored 86.00% in my exams,

index( )
It provides the position of the first occurrence of the substring in the given string.

>>> string1 = "to be or not to be"
>>> string1.index('not')
9
>>>

isalnum( )

It returns true if a string is alphanumeric else it returns false.

>>> string1 = "12321$%%^&*"
>>> string1.isalnum( )
False
>>> string1 = "string1"
>>> string1.isalnum()
True
>>>

isalpha( )

It returns true if the whole string has characters or returns false.

>>> string1.isalpha( )
False
>>> string1 = "tobeornottobe"
>>> string1.isalpha( )
True
>>>

isdeimal( )

Returns true if the string has all decimal characters.

>>> string1 = "874873"
>>> string1.isdecimal()
True

isdigit( )

Returns true if all the characters of a string are digits:

>>> string1 = "874a873"
>>> string1.isdigit()
False
>>>

islower( )

>>> string1 = "tIger"
>>> string1.islower()
False
>>>

isnumeric( )

Returns true if the string is not empty characters of a string are numeric.

>>> string1 = "45.6"
>>> string1.isnumeric()
False
>>>

isspace( )

Returns true if the string only has space.

>>> string1 =" "
>>> string1.isspace()
True
>>>

lower( )

Converts upper case letters to lower case.

>>> string1 ="TIGER"
>>> string1.lower()
'tiger'
>>>

swapcase( )

Changes lower case letters in a string to upper case and vice-versa.

>>> string1 = "tiger"
>>> string1 = "tiger".swapcase()
>>> string1
'TiGER'
>>>

Question 34.
What are execution or escape sequence characters?
Answer:
Characters such as alphabets, numbers, or special characters can be printed easily. However, whitespaces such as line feed, tab, etc. cannot be displayed like other characters. In order to embed these characters, we have used execution characters. These characters start with a backslash character (\) followed by a character as shown in the following code:

1. \n stands for the end of the line.
>>> print(“Happy \nBirthday”)
Happy
Birthday
2. \\ prints backslash – ‘V
. >>> print(‘\\’)
\
3. \t prints a tab
>>> print(“Happy\tBirthday”)
Happy Birthday

Lists

  • • Lists are ordered and changeable collections of elements.
  • • Can be created by placing all elements inside a square bracket.
  • • All elements inside the list must be separated by a comma
  • • It can have any number of elements and the elements need not be of the same type.
  • • If a list is a referential structure which means that it actually stores references to the elements.
  • Lists are zero-indexed so if the length of a string is “n” then the first element will have an index of 0 and the last element will have an index of n-1.
  • Lists are widely used in Python programming.
  • Lists are mutable therefore they can be modified after creation.

Question 35.
What is a list?
Answer:
A list is an in-built Python data structure that can be changed. It is an ordered sequence of elements and every element inside the list may also be called an item. By ordered sequence, it is meant that every element of the list can be called individually by its index number. The elements of a list are enclosed in square brackets[ ].

>>> # Create empty list
>>> list1 = [ ] 
>>> # create a list with few elements
>>> list 2 = [12, "apple" , 90.6,]
>>> list1
[ ] 
>>>list2
[12 , 'apple' , 90.6]
>>>

Question 36.
How would you access the 3rd element of the following list?

list1= ["h","e","1","p"]

What would happen when you try to access list1 [4]?
Answer:
The third element of list1 will have an index of 2. Therefore, we can access it in the following manner:

>>> list1 = ["h","e","1","p"]
>>> list1 [2]
'1'
>>>

There are four elements in the list. Therefore, the last element has an index of 3. There is no element at index 4. On trying to access list1 [4] you will get an “IndexError: list index out of range”

Question 37.
list1 = [”h”,”e”,”I”,”p”]. What would be the output for list1 [-2] and list1 [-5]?
Answer:
list1 [-2] = T
list1 [-5] will generate IndexError: list index out of range
Similar to Strings, the slice operator can also be used on the list. So, if the range given is [a:b]. It would mean that all elements from index a to index b will be returned. [a:b:c] would mean all the elements from index a to index b, with stride c.

Question 38.
list1 = [“l”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
What would be the value for the following?

  1. list1 [5]
  2. list1 [-5]
  3. list1 [3:6]
  4. list1 [:-3]
  5. list1[-3:]
  6. list1 [:]
  7. list1 [1:8:2]
  8. list1 [::2]
  9. list1[4::3]

Answer:

>>> list1 = ["I","L","O","V","E","p","Y","T","H","O","N"]
>>> list1 [5]
'p'
>>> list1 [-5]
'Y'
>>> list1 [3:6]
['V' , 'E' , 'P']
>>> list1 [:-3]
['I' , 'L' , 'O' ,'V' , 'E' , 'P' , 'Y' , 'T']
>>> list1 [-3:]
['H' , 'O' , 'N']
>>> list1 [:]
['I' , 'L' , 'O' ,'V' , 'E' , 'P' , 'Y' , 'T' , 'H' , 'O' , 'N' ]
>>> list1 [1:8:2]
['L' ,'V' , 'P' , 'T' ,]
>>> list1[: :2]
['I' , 'O' , 'E' , 'Y' , 'H' , 'N']
>>> list1 [4 : :3]
['E' , 'T' , 'N']
>>>

Question 39.
list1 = [“I”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
list2 = [‘O’,’N’,’L’ , ‘Y’]
Concatenate the two strings.
Answer:

>>> list1 = list1+list2
>>> list1
['I' list1 , 'L' 'O' 'V' 'E' , 'P' , 'Y' , 'T' , 'H' , 'O' , 'N' , 'O' , 'N' , 'L' , 'Y' ]
>>>

Question 40.
How can you change or update the value of the element in a list?
Answer:
You can change the value of an element with the help of the assignment operator (=).

>>> list1 = [1,2,78,45,93,56,34,23,12,98,70]
>>> list1 = [1,2,78,45,93,56,34,23,12,98,70]
>>> list1 [3]
45
>>> list1[3]=67
>>> list1 [3]
67
>>> list1
[1,2,78,45,93,56,34,23,12,98,70]
>>>

Question 41.
list1 =[1,2,78,45,93,56,34,23,12,98,70]
list1[6:9]=[2,2,2]
What is the new value of list1?
Answer:
[1,2, 78, 45, 93, 56, 2, 2, 2, 98, 70]

Question 42.
What is the difference between append( ) and extend( ) function for lists?
Answer:
The append( ) function allows you to add one element to a list whereas extending ( ) allows you to add more than one element to the list.

>>> list1 = [1,2, 78,45,93,56,34,23,12,98,70]
>>> list1.append(65)
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]

>>> list1.extend([-3,- 5, - 7 , -5] )
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, -3, -5, -7, -5]
>>>

Question 43.
list1 = [“h”,”e”,”l”,”p”]
What would be the value of list1 *2?
Answer:
[‘h’, ‘e’, T, ‘p’, ‘h’, ‘e’, ‘l’ , ‘p’]

Question 44.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 +=[87]
What is the value of list1?
Answer:
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, 87]

Question 45.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 -=[65]
What will be the output?
Answer:
The output will be TypeError: unsupported operand type(s) for -=: ‘list’ and ‘list’

Question 46.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
How will you delete second element from the list?
Answer:
An element can be deleted from a list using the ‘del’ keyword.

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> del(list1 [1])
>>> list1
[1, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 47.
list1 = [[1,4,5,9],[2,4,7,8,1]]
list1 has two elements, both are lists.
How will you delete the first element of the second list contained in the list1?
Answer:

>>> list1 = [ [1,4,5,9] , [2,4,7,8, 1] ]
>>> del(list1[1][0])
>>> list1
[[1, 4, 5, 9] , [4, 7, 8, 1] ]
>>>

Question 48.
How would you find the length of o list?
Answer:
The len( ) function is used to find the length of a string.

>>> list1 = [1, 2, ‘78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> len(list1)
12
>>>

Question 49.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Insert a value 86 at 5th position.
Answer:

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>list1 . insert (4, 86)
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 50.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Remove the value 78 from list1.
Answer:
A specific element can be removed from a list by providing the value to remove( ) function.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . remove (78)
>>> list1
[1,2,45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 51.
What does the pop( ) function do?
Answer:
The pop( ) function can be used to remove an element from a particular index and if no index value is provided, it will remove the last element. The function returns the value of the element removed.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . pop(3)
45
>>> list1
[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . pop( )
65
>>> list1
[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70]
>>>

Question 52.
Is there a method to clear the contents of a list?
Answer:
Contents of a list can be cleared using the clear( ) function.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . clear ( )
>>> list1
[ ]
>>>

Question 53.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Find the index of element having value 93.
Answer:
We can find the index of a value using the index( ) function.

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1.index(93)
4
>>>

Question 54.
Write code to sort list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65].
Answer:
We can sort a list using sort( ) function.

>>> list1 = [1,2,78,45,93,56,34,23,12,98,70,65]
>>> list1 . sort ( )
>>> list1
[1,2,12,23,34,45,56,65,70,78,93,98]
>>>

Question 55.
Reverse elements of list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65].
Answer:

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . reverse ( )
>>> list1
[65,70,98,12,23,34,56,93,45,78,2,1]
>>>

Question 56.
How can we check if an element exists in a list or not?
Answer:
We can check if an element exists in a list or not by using ‘in’ keyword:

>>> list1 = [(1,2,4) , [18,5,4,6,2] , [4,6,5,7], 9, 23, [98, 56] ]
>>> 6 in list1
False
>>> member = [4,6,5,7]
>>> member in list1
True
>>>

tuples

  • tuples are sequences just like lists but are immutable.
  • Cannot be modified.
  • tuples may or may not be delimited by parenthesis ( ).
  • Elements in a tup1e are separated by a comma. If a tuple has only one element then a comma must be placed after that element. Without a trailing comma, a single value in simple parenthesis would not be considered as a tuple.
  • Both tup1es and lists can be used under the same situations.

Question 57.
When would you prefer to use a tup1e or a list?
Answer:
tup1es and lists can be used for similar situations but tup1es are generally preferred for the collection of heterogeneous data types whereas lists are considered for homogeneous data types. Iterating through a tup1e is faster than iterating through a list. tup1es are ideal for storing values that you don’t want to change. Since tup1es are immutable, the values within are write-protected.

Question 58.
How can you create a tup1e?
Answer:
A tup1e can be created in any of the following ways:

>>> tup1 =( )
>>> tup2=(4 , )
>>> tup3 = 9,8,6,5
>>> tup4= (7,9,5,4,3).
>>> type(tup1)
<class ' tup1e' >
>>> type(tup2)
<class 'tup1e'>
>>> type(tup3)
<class ' tup1e' >
>>> type(tup4)
<class 'tup1e'>

However, as mentioned before, the following is not a case of a tup1e:

>>> tup5 = (0)
>>> type(tup5)
1cclass 'int'>
>>>

Question 59.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
How would you retrieve the 7th element of this tup1e?
Answer:
Accessing an element of a tup1e is the same as accessing an element of a list.

>>> tup1 = (1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
>>> tup1 [6]
34
>>>

Question 60.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would happen when we pass an instruction tup1[6]=6?
Answer:
A tup1e is immutable hence tup1 [6]=6 would generate an error.

Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
tup1[6]=6
TypeError: 'tup1e' object does not support item
assignment
>>>

Question 61.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would happen if we try to access the 6th element using tup1 [5.0]?
Answer:
The index value should always be an integer value and not afloat. This would generate a type error. TypeError: ‘tup1e’ object does not support item assignment.

Question 62.
tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
What would be the value of tup1 [1 ][0]?
Answer:
8

Question 63.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What is the value of tup1 [-7] and tup1 [-15]?
Answer:

>>> tup1[-7]
56
>>> tup1[-15]
Traceback (most recent call last) :
File "<pyshell#2>", line 1, in <module> tup1 [-15]
IndexError: tup1e index out of range
>>>

Question 64.
tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
tup2 = (1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
Find the value of:

  1. tup1[2:9]
  2. tup2[:-l]
  3. tup2[-l:]
  4. tup1[3:9:2]
  5. tup2[3:9:2]

Answer:
1. tup1 [2:9]
((4, 6, 5, 7), 9, 23, [98, 56])
2. tup2[:-l]
(1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70)
3. tup2[-l:]
(65,)
4. tup1[3:9:2]
(9, [98, 56])
5. tup2[3:9:2]
(45, 56, 23)

Question 65.
tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
What will happen if tup1[l][0]=18 instruction is passed? What would happen if we pass an instruction tup1 [l].append(2)?
Answer:
tup 1 [ 1 ] is a list object and the list is mutable.
a tuple is immutable but if an element of a tup1e is mutable then its nested elements can be changed.

>>> tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
>>> tup1 [1] [0] = 18
>>> tup1 [1]
[18 , 5, 4, 6 ]
>>> tup1 [1] . append (2)
>>> tup1
((1,2,4) , [8,5,4,6],(4,6,5,7),9,23,[98,56] , 1,2,78,45, 93,56,34,23,12,98,70,65)
>>>

Question 66.
tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
tup2 =(1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would be the output for tup1+tup2?
Answer:

>>> tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
>>> tup2 = (1,2,78,45,93,56,34,23,12,98,70,65)
>>> tup1+tup2
>>> tup1
( (1,2,4) , [18,5,4,6,2] , (4,6,57), 9,23,[98,56], 1,2,78,45, 93, 56, 34,23,12,98,70,65)
>>>

Question 67.
How can we delete a tup1e?
Answer:
A tup1e can be deleted using del command.

>>> tup1 = (1,2,4), [8,5,4,61 , (4,6,5,7) ,9,23, [98,56]
>>> del tup1
>>> tup1
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
tup1
NameError: name 'tup1' is not defined
>>>

Question 68.
tup1 = ((1, 2, 4), [18, 5, 4, 6, 2], (4, 6, 5, 7), 9, 23, [98, 56])
tup2 = 1,6,5,3,6,4,8,30,3,5,6,45,98
What is the value of:

  1. tup1.count(6)
  2. tup2.count(6)
  3. tup1.index(6)
  4. tup2.index(6)?

Answer:
1. tup1.count(6)
0
2. tup2.count(6)
3
3. tup1.index(6)
0
4. tup2.index(6)
1

Question 69.
How can we test if an element exists in a tup1e or not?
Answer:
We can check if an element exists in a tup1e or not by using in a keyword:

>>> tup1 = ((1, 2, 4), [18, 5, 4, 6, 2], (4, 6, 5, 7) , 9, 23, [98, 56] )
>>> 6 in tup1
False
>>> member = [4,6,5,7]
>>> member in tup1
False
>>> member2 = (4, 6, 5, 7)
>>> member2 in tup1
True
>>>

Question 70.
How can we get the largest and the smallest value in tup1e?
Answer:
We can use max( ) function to get the largest value and min() function to get the smallest value.

>>> tup1 = (4, 6, 5, 7)
>>> max(tup1)
7
>>> min(tup1)
1 4
>> >

Question 71.
How to sort all the elements of a tup1e?
Answer:

>>> tup1 =(1,5,3,7,2,6,8,9,5,0,3,4,6,8)
>>> sorted(tup1)
[0, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9]

Question 72.
How can we find the sum of all the elements in a tup1e?
Answer:
We can find some of all elements by using the sum( ) function.

>>> tup1 =(1,5,3,7,2,6,8,9,5,0,3,4,6,8)
>>> sum(tup1)
67

Enumerate function for tup1e and list in for loop section mentioned.

Dictionary

  • Unordered sets of objects.
  • Also known as maps, hashmaps, lookup tables, or associative array.
  • Data exists in key-value pair. Elements in a dictionary have a key and a corresponding value. The key and the value are separated from each other with a colon’: ’ and all elements are separated by a comma.
  • Elements of a dictionary are accessed by the “key” and not by index. Hence it is more or less like an associative array where every key is associated with a value .and elements exist in an unordered fashion as key-value pair.
  • Dictionary literals use curly brackets ‘ { } ’.

Question 73.
How can we create a dictionary object?
Answer:
A dictionary object can be created in any of the following ways:

>>> dictl = { }
>>> type(dict1)
<class 'dict'>

>>> dict2 = {'key1' :'value1', 'key2': 'value2', 'key3': 'value3', ' key4': ' value4'}
>>> dict2
{'key1': 'value1', 'key2': 'value2', 'key3' : 'value3', 'key4': 'value4' }
>>> type(dict2)
<class 'diet'>

>>> dict3 = diet({'key1': 'value1', 'key2':' value2', 'key3': 'value3', ' key4 ':' value4' })
>>> dict3
{'key1': 'value1', 'key2' : 'value2', 'key3': 'value3', 'key4':'value4'}
>>> type(dict3)
<class 'diet'>

>>> dict4 = diet(f('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3 ' ), ('key4','value4')])
>>> dict4 {'key1': 'value1' 'key2' : 'value2', 'key3': 'value3', 'key4':' value4'}
>>> type(dict4)
<class 'diet'>

Question 74.
How can you access the values of a dictionary?
Answer:
Values of a dictionary can be accessed by the help of the keys as shown in the following code:

>>> student_dict = {'name':'Mimoy', 'Age':12, 'Grade' :7, 'id' :'7102' }
>>> student_dict['name']
'Mimoy'

Keys are case-sensitive. If you give student diet [‘age’] instruction a key Error will be generated because the key actually has capital A in Age. The actual key is Age and not age.

>>> student_dict['age' ]
Traceback (most recent call last) -.
File "<pyshell#20>", line 1, in <module>
student_dict['age']
KeyError: 'age'
>>> student_dict['Age']
12
>>>

Question 75.
Can we change the value of an element of a dictionary?
Answer:
Yes, we can change the value of an element of a dictionary because dictionaries are mutable.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'} .
>>> dict1['English literature'] = '78%'
>>> dict1
{'English literature': '78%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' }
>>>

Question 76.
Can a dictionary have a list as a key or a value?
Answer:
A dictionary can have a list as a value but not as a key.

>>> dict1 = {'English literature':'67%','Maths':'78% ','Social Science':'87%','Environmental Studies': 97%' }
>>> dictl['English literature' >>> dict1] = ['67% ,'78%']
{'English literature': ['67%', '78%'], Maths': '78%', 'Social Science': '87%' , 'Environmental Studies' : '97%' }
>>>

If you try to have a list as a key then an error will be generated:

>>> dict1 = {['67%', '78%']:'English literature', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%'}
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
dict1 = {['67%', '78%']:'English literature',
'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%'}
TypeError: unhashable type: 'list'
>>>

Question 77.
How are elements deleted or removed from a dictionary?
Answer:
Elements can be deleted or removed from a dictionary in any of the following ways:

>>> dict1 = {‘English literature’:’67%YMaths’:’78%’, ’Social Science’: ’ 87%’, ’Environmental Studies ’: ’ 97% ’}

I. The pop( ) can be used to remove a particular value from a dictionary. pop( ) requires a valid key-value as an argument or you will receive a key error. If you don’t pass any argument then you will receive a type error: “TypeError: descriptor ‘pop’ of ‘diet’ object needs an argument”

>>> dict1.pop('Maths' )
'78%'
>>> dict1
{'English literature' '67%', 'Social Science': '87%', 'Environmental Studies' : '97%'}

II. The pop item( ) can be used to remove any arbitrary item.

>>> dict1.popitem( )
('Environmental Studies', '97%')
>>> dict1
{'English literature': '67%', 'Social Science': '87%' }

III. Yod can delete a particular value from a dictionary using the ‘del’ keyword.

>>> del dict1['Social Science']
>>> dict1
{'English literature': '67%'}

IV. clear( ) function can be used to clear the contents of a dictionary.

>>> dict1.clear( )
>>> dict1
{ }

V. The del( ) function can also be used to delete the whole dictionary after which if you try to access the dictionary object, a Name Error will be generated as shown in the following code:

>>> del dict1
>>> dict1
Traceback (most recent call last):
File "<pyshell#ll>" , line 1, in <module>
dict1
NameError: name 'dict1' is not defined
>>>

Question 78.
What is the copy( ) method used for?
Answer:
A copy method creates a shallow copy of a dictionary and it does not modify the original dictionary object in any way.

>>> dict2 = dict1.copy()
>>> dict2
{'English literature': '67%', 'Maths': ' 78%', 'Social Science': '87%','Environmental Studies': ' 97%'}
>>>

Question 79.
Explain from Keys( ) method.
Answer:
The from keys( ) method returns a new dictionary that will have the same keys as the dictionary object passed as the argument. If you provide a value then all keys will be set to that value or else all keys will be set to ‘None.

I. Providing no value
>>> dict2 = diet.fromkeys(dict1)
>>> dict2
{‘English literature’: None, ‘Maths’: None, ‘Social Science’ : None, ‘Environmental Studies’ : None}
>>>

II. Providing a value
>>> dict3 = diet.fromkeys(dictl,’90%’)
>>> dict3
{‘English literature’: ‘90%’, ‘Maths’: ‘90%’,
‘Social Science’: ‘90%’, ‘Environmental Studies’: ‘90%’ }
>>>

Question 80.
What is the purpose of items( ) function?
Answer:
The items( ) function does not take any parameters. It returns a view object that shows the given dictionary’s key-value pairs.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'}
>>> dictl.items()
dict_items([('English literature', '67%'),
('Maths', '78%'), ('Social Science', '87%'), ('Environmental Studies', '97%')])
>>>

Question 81.
dict1 = {(1,2,3):[‘1’,’2’,’3’]}
Is the instruction provided above, a valid command?
Answer:
dict1 = {(l,2,3):[‘r,’2’,’3’]} is a valid command. This instruction will create a dictionary object. In a dictionary, the key must always have an immutable value. Since the key is a tup1e which is immutable, this instruction is valid.

Question 82.
dict_items([(‘English literature’, ‘67%’), (‘Maths’, ‘78%’), (‘Social Science’, ‘87%’), (‘Environmental Studies’, ‘97%’)]).
Which function can be used to find the total number of key-value pairs in dict1?
Answer:
The len( ) function can be used to find the total number of key-value pairs.

>>> dictl = {'English literature' :' 67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'}
>>> len(dict1)
4
>>>

Question 83.
dict1 = {‘English literature’:’67%’,’ Maths’:’78%’,’ Social Science’:’87%’,’ Environmental Studies’:’97%’}
dict1 .keys( )
What would be the output?
Answer:
The keys( ) function is used to display a list of keys present in the given dictionary object.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dictl.keys( )
dict_keys(['English literature', 'Maths', 'Social Science', 'Environmental Studies'])
>>>

Question 84.
dict1 = {‘English literature’:’67%’,’ Maths’:’78%’,’ Social Science’:’87%’,’ Environmental Studies’:’97%’}
‘Maths’ in dict1
What would be the output?
Answer:
True

The ‘in’ operator is used to check if a particular key exists in the diet or not. If the key exists then it returns ‘True’ else it will return ‘False’.

Question 85.
dict1 = {‘English literature’:’67%’,’Maths’:’78%’,’Social Science’:’87%’,’Environmental Studies’:’97%’}
dict2 = {(1,2,3):[‘1’,’2’,’3’]}
dict3 = {‘Maths’: ‘78%’}
dict4= {‘Maths’: ‘98%’,’Biology’:’56%’}
What would be the output of the following:

  1. dict1.update(dict2)
  2. dict2={(l,2,3):[‘l\’2Y3’]}
  3. dict3 ,update(dict3)
  4. dict1.update(dict4)

Answer:
The update( ) method takes a dictionary object as an argument. If the keys already exist in the dictionary then the values are updated and if the key does not exist then the key-value pair is added to the dictionary.

>>> dict1 = { 'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dict2 = { (1,2,3) : [ '1' , ' 2' , ' 3' ] }
>>> dict1.update(dict2)
>>> dict1
{'English literature': '67%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' , (1, 2, 3) : ['1' , '2' , '3' ] }
dict1 = {'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dict3 = { 'Maths' : '78%' }
>>> dict1 .update (dict3)
>>> dict1
{'English literature': '67%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' }
dict3 = {'Maths' : '78%' }
>>> dict3.update(dict3)
>>> dict3 {'Maths' : '78%' }
dict1 = {'English
literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'} dict4 = {'Maths': '98%','Biology':'56%'}
dictl.update(dict4) dictl
{'English literature' '67%', 'Maths': '98%',
'Social Science': '87%', 'Environmental Studies':
'97%.', 'Biology': '56%'}

Question 86.
dictl = {‘English literature’:’67%\’Maths’:78%\’Social Science’:’87%’,‘Environmental Studies’:’97%’}
dictl.values( )
What will be the output?
Answer:

>>> dictl.values( )
diet values (['67%', ' 78%' ' 87%' '97%'])
>>>

Sets

  • An unordered collection of items
  • Every element is unique and immutable
  • Set itself is mutable
  • Used for performing set operations in Math
  • Can be created by placing all the items in curly brackets {}, separated by ‘ , ‘
  • Set can also be created using the inbuilt set() function
>>> set1 ={8,9,10}
>>> set1
{8, 9, 10}
>>>
  • Since sets are unordered, indexing does not work for it

Question 87.
How can we create an empty set?
Answer:
The inbuilt function set( ) is used to create an empty set. Empty curly braces cannot be used for this task as it will create an empty dictionary object.

Question 88.
How can we add a single element to a set?
Answer:
We can add a single element with the help of add() function.

>>> set1 ={12,34,43,2}
>>> set1 . add(32)
>>> set1
(32, 2, 34, 43, 12}
>>>

Question 89.
How can we add multiple values to a set?
Answer:
Multiple values can be added using update( ) function.

>>> set1 ={12,34,43,2}
>>> set1.update( [76,84,14,56])
>>> set1
{2, 34, 43, 12, 76, 14, 84, 56}
>>>

Question 90.
What methods are used to remove value from sets?
Answer:
(1) discard( )
(2) remove ( )

Question 91.
What is the purpose of pop() method?
Answer:
The pop( ) function randomly removes an element from a set.

Question 92.
How can we remove all elements from a set?
Answer:
All elements from a set can be removed using the

>>> set1 = {2, 34, 43, 12, 76, 14, 84, 56}
>>> set1.clear( )
>>> set1
set ( )

Question 93.
What are various set operations?
Answer:

>>> #Union of two sets
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl | set2
{1, 3, 4, 5, 6, 7, 10, 12, 15}
>>> #Intersection of two sets
>>> set1 = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl & set2 {10, 3, 7}
>>> #Set difference
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl - set2
{1, 4, 5, 6} .
>>> #Set symmetric difference
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> set1∧set2
{1, 4, 5, 6, 12, 15}
>>>

Python Data Types

Question 94.
What are some of the built-in data types available in Python?
Answer:

  • Integer,
  • float,
  • long integer,
  • octal integer,
  • hexadecimal integer,
  • complex,
  • string,
  • list,
  • dictionary,
  • tuple,
  • file.

Question 95.
What is the difference between a tuple and a list?
Answer:
A tuple is immutable, it cannot be added to, rearranged, nor have items removed. It is faster to access and use than a list but it cannot be manipulated.

Question 96.
What are some of the specialized container types that are new in Python since 2.4?
Answer:
Namedtuple( ), deque, Counter, OrderedDict and defaultdict.

Question 97.
Illustrate defining a list.
Answer:
myList = [1, 2, “three”, 4] or myList = [ “I”, “Love”, “Python”] etc.

Question 98.
Write a code fragment that illustrates accessing a list by index.
Answer:
mylndex = 0
while mylndex < len(myList): print mylndex, ‘, myListlmylndex] mylndex++

Question 99.
What exception is raised when a negative index is used to access a list?
Answer:
Tricky question: Negative indexes are allowed in Python, it accesses the list from the bottom rather than the top. An index of -1 accesses the last item in the list, -2 the second to last, and so on.

Question 100.
Can a list contain other lists?
Answer:
Yes. A list can contain objects of any type.

Question 101.
How is a sublist accessed?
Answer:
The form is listname[listindex][sublistindex]. For example, myList[0][5] would retrieve the fifth item from the first sublist in myList.

Question 102.
How is a list sliced? Provide an example.
Answer:
By using the start, colon, end syntax. myList[5:10] This would return a list containing the 6th through 11th items in my list.

Question 103.
How would you add an item to an unsorted list?
Answer:
Using the append method. myList.append(theNexuItem)

Question 104.
How would you add an item to a sorted list in a specific position?
Answer:
Using the list insert method. myList.insert(index, theNewItem)

Question 105.
How would you remove an item from the list, if you know its index?
Answer:
Using the .pop list method. myList.pop(2) would remove the third item in my list.

Question 106.
How would you combine one list with another?
Answer:
Using the extend list method. myList.extend(theOtherList)

question 107.
How would you alphabetize a simple list of strings?
Answer:
Using the built-in sort method. myList.sort( )

Question 108.
How is a tuple created?
Answer:
myTuple = (“First item”, “Second Item”)

Question 109.
How is a tuple converted to a list, and a list to a tuple?
Answer:
Using the built-in functions list and tuple. myTuple = tuple(myList) and myList = list(myTuple) a

Question 110.
What is a dictionary and how is it constructed?
Answer:
A dictionary is a list containing name / value pairs.
myDict = {firstKey: firstValue, secondKey : secondValue } a

Question 111.
How is dictionary value retrieved?
Answer:
The usual method is to specify the key value in brackets. myDict[myKey] will return the value associated with myKey in the dictionary.

Question 112.
How are values added to a dictionary? Illustrate with an example.
Answer:
By creating a new key, and assigning a value to it.
myDict[myNewKey] = myNewValue

Question 113.
Can a dictionary contain lists or other dictionaries?
Answer:
Yes. The values assigned in a dictionary can be any valid Python object.