Mod2 Python Answers
Mod2 Python Answers
them.
➢ A list is a value that contains multiple values in an ordered sequence.
➢ A list value looks like this: ['cat', 'bat', 'rat', 'elephant'].
➢ A list begins with an opening square bracket and ends with a closing square bracket
The indices of the list are The keys of the dictionary can be of any
integers starting from 0. data type.
The elements are accessed The elements are accessed via key-value
via indices. pairs.
Qu2/9 List and demonstrate various list methods with example for each.
Python offers the following List Methods:
append(): Adds an element to the end of the list.
insert(): Inserts an element at a specified position in the list.
remove(): Removes the first occurrence of an element from the list.
pop(): Removes and returns the element at a specified index.
sort(): Sorts the elements in the list in ascending order.
index() : returns the position at the first occurrence of the specified value.
Qu3 Explain the following methods with example: a. keys() b. values() c. items() d. get() e.
setdefault()
keys():Returns a view object that displays a list of all the keys in the dictionary in order
of insertion
setdefault(): Returns the value of a key if the key is in the dictionary else inserts the key
with a value to the dictionary
values():Updates the dictionary with the elements from another dictionary
get():Returns the value for the given key
items():Return the list with all dictionary keys with values
Qu4 Discuss the following with example: a. Accessing individual elements of list with
indexes. b. Negative indexes. c. List slicing. d. in and not in operators with lists
a) Getting Individual Values in a List with Indexes
Say you have the list ['cat', 'bat', 'rat', 'elephant'] stored in a variable named spam.
The Python code spam[0] would evaluate to 'cat', and spam[1] would evaluate to 'bat',
and so on.
b)Negative Indexes
We can also use negative integers for the index. The integer value -1 refers to the last
index in a list, the value -2 refers to the second-to-last index in a list, and so on.
d) Python’s in and not in operators allow you to quickly determine if a given value is or
isn’t part of a collection of values.
Qu6 Explain various pretty print methods and demonstrate the difference between print()
and pretty print methods with example
The normal print() function prints the entire content in a single line
The pprint() function prints the entire content with pretifying as required and the output
is much formatted and readable way compared to the one printed by print() function.
Qu7 How tuple is different from list and which function is used to convert list to tuple?
Tuples are similar to lists, they are sequences. A tuple is different from lists by tuple can
not be changed and lists on the other hand can be changed also tuples are enclosed in
parentheses, and lists are enclosed in square braces.