Page 318 - AI Ver 1.0 Class 9
P. 318
The insert( ) Function
The insert( ) function is used to add a single value at a specific position in an existing list. The length of the
list will increase by one. Syntax of the insert( ) function is:
list.insert(index, value)
Examples:
Commands Output
L = [10, 20, 30] [10, 40, 20, 30]
L.insert(1, 40)
print(L)
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:
316 Touchpad Artificial Intelligence-IX

