Page 330 - Artificial Intellegence_v2.0_Class_9
P. 330
L.insert(0, "abc") ['abc', 10, 40, 20, 30]
print(L)
a = "xyz" ['abc', 10, 40, 'xyz', 20, 30]
L.insert(3, a)
print(L)
L.insert(5, ["a", "b"]) ['abc', 10, 40, 'xyz', 20, ['a', 'b'], 30]
print(L)
Modifying Existing Values in a List
List is mutable so data can be easily modified by overwriting a new value to an existing value in a given list by
using an assignment operator (=). Syntax to modify existing values in a list is:
list[index] = newvalue
Example:
Commands Output
l1=[10,20,40,50] [10, 20, 40, 100]
l1[3]=100
print(l1)
l1[1:3]=["abc","xyz"] [10, 'abc', 'xyz', 100]
print(l1)
Removing Elements from a List
There are two different functions used to remove elements in an existing list remove() and pop(). Let us learn
about these functions in detail.
The remove( ) Function
The remove() function removes the first occurrence of the element with the specified value. It means only
one value can be removed at a time even if there are duplicate values in the list. If you wish to remove multiple
values then this function can be used within a loop where it repeats itself a specific number of times. Syntax of
the remove() function is:
list.remove(<single value>)
For example,
Commands Output
marks = [23, 34, 23, 45, 56, 78, 56] marks = [34, 23, 45, 56, 78, 56]
marks.remove(23)
print(marks)
marks.remove(56) marks = [34, 23, 45, 78, 56]
print(marks)
marks.remove(72) ValueError: list.remove(x): x not in list
328 Touchpad Artificial Intelligence (Ver. 2.0)-IX

