Python Module2 Answers
Python Module2 Answers
Python Module2 Answers
1. Explain indexing in List. When do we encounter TypeError, ValueError and IndexError while
operating on Lists?
The index() method returns the position at the first occurrence of the specified value.
Syntax
list.index(elmnt)
Parameter Values
Parameter Description
elmnt Required. Any type (string, number, list, etc.). The element to search for
Example
What is the position of the value 32:
fruits = [4, 55, 64, 32, 16, 32] Output: 3
x = fruits.index(32)
print(x)
The index() method only returns the first occurrence of the value.
Type error:-
Indexes can be only integer values, not floats. The following example will cause a TypeError error:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[1]
'bat'
>>> spam[1.0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers or slices, not float
>>> spam[int(1.0)]
'bat'
Indexing Error
Python will give you an IndexError error message if you use an index that exceeds the number of values
in your list value.
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
spam[10000]
IndexError: list index out of range
Value error
The multiple assignment trick (technically called tuple unpacking) is a shortcut that lets you assign multiple
variables with the values in a list in one line of code. So instead of doing this:
1
C Prathibha, Asst.Prof., E&C Dept, KIT Module2 21EC643
For example:
my_list = [1, 2, 3, 4, 5]
my_list[2] = 10
In the above code, the third element of the list (with index 2) is modified to have a new value of 10. This
modification can be done on any element of the list, regardless of its position. Adding and Removing
Elements Lists also allow for the addition and removal of elements. New elements can be added to the end
of the list using the `append()` method or inserted at a specific position using the `insert()` method. Elements
can be removed from the list using the `remove()` method or by using the `del` keyword followed by the
index of the element to be deleted.
python
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Add 6 to the end of the list
my_list.insert(2, 7) # Insert 7 at index 2
my_list.remove(4) # Remove the element with value 4 del
my_list[0] # Delete the element at index 0
These operations demonstrate the mutability of lists. The list can be modified by adding or removing
elements as needed, resulting in a different list structure.
3. Consider the list scores = [5, 4, 7, 3, 6, 2, 1] and write the python code to perform the following
operations:
i. Insert an element 9 at the beginning of the list.
ii. Insert an element 8 at the index position 3 of the list.
iii. Insert an element 7 at the end of the list.
iv. Delete all the elements of the list.
2
C Prathibha, Asst.Prof., E&C Dept, KIT Module2 21EC643
Adding Values to Lists with the append() and insert() Methods:-To add new values to a list, use
the append() and insert() methods. Enter the following into the interactive shell to call the append() method
on a list value stored in the variable spam:
3
C Prathibha, Asst.Prof., E&C Dept, KIT Module2 21EC643
Removing Values from Lists with the remove() Method:-The remove() method is passed the value to be
removed from the list it is called on. Enter the following into the interactive shell:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('bat')
>>> spam
['cat', 'rat', 'elephant']
Attempting to delete a value that does not exist in the list will result in a ValueError error. For example,
enter the following into the interactive shell and notice the error that is displayed:
>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam.remove('chicken')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
spam.remove('chicken')
ValueError: list.remove(x): x not in list
Sorting the Values in a List with the sort() Method:-Lists of number values or lists of strings can be sorted
with the sort() method. For example, enter the following into the interactive shell:
>>> spam = [2, 5, 3.14, 1, -7]
>>> spam.sort()
>>> spam
[-7, 1, 2, 3.14, 5]
>>> spam = ['ants', 'cats', 'dogs', 'badgers', 'elephants']
>>> spam.sort()
>>> spam
['ants', 'badgers', 'cats', 'dogs', 'elephants']
You can also pass True for the reverse keyword argument to have sort() sort the values in reverse order.
Enter the following into the interactive shell:
>>> spam.sort(reverse=True)
>>> spam
['elephants', 'dogs', 'cats', 'badgers', 'ants']
5. Discuss different ways of traversing a list. Explain with an example for each
There are multiple ways through which we can iterate the list in python programming. Let us study them
one by one below:
list = [1, 2, 3, 4, 5]
4
C Prathibha, Asst.Prof., E&C Dept, KIT Module2 21EC643
list = [1, 2, 3, 4, 5]
# Getting length of list using len() function
length = len(list)
i=0
while i < length:
print(list[i])
i += 1
The output of the above code is as given below:
1
2
3
4
5
5
C Prathibha, Asst.Prof., E&C Dept, KIT Module2 21EC643
list = [1, 2, 3, 4, 5]
# Iterating list using list comprehension
[print(i) for i in list]
The output of the above code is as given below:
1
2
3
4
5
list = [1, 3, 5, 7, 9]
# Using enumerate() function to iterate the list
for i, val in enumerate(list):
print (i, ",",val)
The output of the above code is as given below:
0, 1
1, 3
2, 5
3, 7
4, 9