Mod 2 Solutions
Mod 2 Solutions
MODULE -2
ii. index()
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.
Example:
iii. sort()
Lists of number values or lists of strings can be sorted with the sort()
method
First, the sort() method sorts the list in place; don’t try to return value by
writing code like spam = spam.sort().
Second, we cannot sort lists that have both number values and string
values in them
iv. remove()
The remove () method is passed the value to be removed from the list it is
called on.
If the value appears multiple times in the list, only the first instance of the
value will be removed.
The remove() method is good when you know the value you want to
remove from the list.
Ex:
v. insert()
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
Ex:
2. Explain negative indexing and the use of in and not in operator in the list with
examples
1. Negative Indexing
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
Accessing from the End: Negative indexing allows you to access elements of a
list, string, or tuple from the end.
Reverse Order: While positive indices count from the start (0, 1, 2...), negative
indices count backward (-1, -2, -3...).
For example, -1 refers to the last element, -2 to the second last, and so on.
ii)set default()
To set a value in a dictionary for a certain key only if that key does not
already have a value
The setdefault() method offers a way to do this in one line of code.
Setdeafault() takes 2 arguments:
The first argument is the key to check for, and
The second argument is the value to set at that key if the key does not
exist. If the key does exist, the setdefault() method returns the key’s
value
Example:
2.
3.