Python Module2 Answers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

C Prathibha, Asst.Prof.

, E&C Dept, KIT Module2 21EC643

Kalpataru Institute of Technology


Department of Electronics and Communication Engineering
Python Programming (21EC643)
Even 2024
Question Bank with answers
Faculty :- C Prathibha Semester: - 6th Sec B
Module 2

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

>>> cat = ['fat', 'gray', 'loud']


>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
you could type this line of code:
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition = cat
The number of variables and the length of the list must be exactly equal, or Python will give you
a ValueError:
>>> cat = ['fat', 'gray', 'loud']
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)

2. Lists are Mutable. Justify the statement with examples.


Lists as Mutable Data Type:-In Python, a list is an ordered collection of elements enclosed in square
brackets [ ]. Lists are considered mutable data types because they can be modified or changed after they are
created. This means that the elements of a list can be added, removed, or modified without creating a new
list.
Modifying Elements:- One of the main reasons why lists are called mutable data types is because
individual elements within a list can be modified. This is done by accessing the element using its index
and assigning a new value to it.

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.

Hence Lists are Mutable

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

v. Delete an element at the index position 3.

i. scores = [5, 4, 7, 3, 6, 2, 1] Output: -


# Insert an element 9 at the beginning of the list. [9, 5, 4, 7, 3, 6, 2, 1]
scores.insert(0,9)
print(scores)

ii. Insert an element 8 at the index position 3 of the list.


scores = [5, 4, 7, 3, 6, 2, 1] Output: -
# Insert an element 8 at the index position 3 of the list. [5, 4, 7, 8, 3, 6, 2, 1]
scores.insert(3,8)
print(scores)

iii. Insert an element 7 at the end of the list.


scores = [5, 4, 7, 3, 6, 2, 1] Output: -
# Insert an element 7 at the end of the list. [5, 4, 7, 3, 6, 2, 1, 7]
scores.append(7)
print(scores)

iv. Delete all the elements of the list. Output:-


scores = [5, 4, 7, 3, 6, 2, 1] []
# Delete all the elements of the list.
scores.clear()
print(scores)
Output:-
v. Delete an element at the index position 3. [5, 4, 7, 6, 2, 1]
scores = [5, 4, 7, 3, 6, 2, 1]
# Delete an element at the index position 3.
del scores[3]
print(scores)

4. Explain the various list methods with examples.


Finding a Value in a List with the index() Method:-List values have an index() method that can be passed
a value, and if that value exists in the list, the index of the value is returned. If the value isn’t in the list,
then Python produces a ValueError error. Enter the following into the interactive shell:
>>> spam = ['hello', 'hi', 'how', 'hey']
>>> spam.index('hey')
3
>>> spam.index('how how how')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
spam.index('how how how')
ValueError: 'how how how' is not in list
When there are duplicates of the value in the list, the index of its first appearance is returned. Enter the
following into the interactive shell, and notice that index() returns 1, not 3:
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1

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

>>> spam = ['cat', 'dog', 'bat']


>>> spam.append('moose')
>>> spam
['cat', 'dog', 'bat', 'moose']
The previous append() method call adds the argument to the end of the list. The insert() method can insert
a value at any index in the list. The first argument to insert() is the index for the new value, and the
second argument is the new value to be inserted. Enter the following into the interactive shell:
>>> spam = ['cat', 'dog', 'bat']
>>> spam.insert(1, 'chicken')
>>> spam
['cat', 'chicken', 'dog', 'bat']

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:

Using for loop


The easiest method to iterate the list in python programming is by using them for a loop. The method of the
iterating list using for loop is as given below

list = [1, 2, 3, 4, 5]
4
C Prathibha, Asst.Prof., E&C Dept, KIT Module2 21EC643

# Iterating list using for loop


for i in list:
print(i)
The output of the above code is as given below:
1
2
3
4
5

Using loop and range() function


Another method to iterate the list while programming in python is by using the loop and range() function
together. Iterating the list using this method is not recommended if iteration using for loop(method 1) is
possible. The method to do so is as given below:
list = [1, 2, 3, 4, 5]
# getting length of list using len() function
length = len(list)

# using for loop along with range() function


for i in range(length):
print(list[i])

The output of the above code is as given below:


1
2
3
4
5

Using While loop


We can also iterate the list in python language using a while loop. The method to use while loop for the
iterating list is as given below:

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

Using list comprehension


This is the most concrete way to iterate the list while programming in the python language. The method to
iterate list using list comprehension is as given below:

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

Using enumerate() function


There are few times when you may need the display the index of the element along with the element in the
list itself. In such cases, we use the enumerate() function for the iteration of the list. The method to use the
enumerate() function to iterate the list is as given below:

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

You might also like