Page 329 - Artificial Intellegence_v2.0_Class_9
P. 329
#input names of 5 friends and store in list Enter Friend Name :Amit
friends=[] Enter Friend Name: Sneha
for i in range(5): Enter Friend Name: Swati
nm=input("Enter Friend Name: ") Enter Friend Name: Sudhir
friends.append(nm) Enter Friend Name: Shashi
print(friends) ["Amit", "Sneha", "Swati", "Sudhir", "Shashi"]
#adding a list at the end of another list ['cat', 'dog', 'rabbit', ['tiger', 'lion']]
pets = ['cat', 'dog', 'rabbit']
wild = ['tiger', 'lion']
pets.append(wild)
print(pets)
The extend( ) Function
The extend() Function is used to append multiple values at a time in a list. Syntax of the extend()
function is:
list.extend(iterable value)
where iterable value can be a list. Examples are:
Commands Output
n=[1,2,3,4] [1, 2, 3, 4, 5]
m=[5]
n.extend(m)
print(n)
pets = ['cat', 'dog', ['cat', 'dog', 'rabbit', 'tiger', 'lion']
'rabbit']
wild=['tiger', 'lion']
pets.extend(wild)
print(pets)
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)
Introduction to Python 327

