Page 255 - Ai_V1.0_Class9
P. 255
To display['C', 'A', 'T'] from the print(word[3:6]) ['C', 'A', 'T']
above list or
print(word[-6:-3])
or
print(word[3:-3])
To display ['O', 'I', 'T'] from the print(word[7:4:-1]) ['O', 'I', 'T']
above list or
print(word[-2:-5:-1])
or
print(word[7:-5:-1])
or
print(word[-2:4:-1])
To display the list in reverse order print(word[::-1]) ['N', 'O', 'I', 'T', 'A', 'C', 'U', 'D', 'E']
Adding New Elements to a List
There are three different functions used to add elements in an existing list which are append( ),
extend( ) and insert( ). Let us learn about them in detail.
The append( ) Function
The append( ) function appends a single element with the given value(any datatype) at the end of the list. We
use this function in a loop for adding multiple elements. With the single append( ) function, the length of the
list will increase by 1. The syntax of the append( ) function is:
list.append(item)
where, item can be any value like number, string, list, etc. For example,
Commands Output
fruits = ["apple", "banana", "cherries"] ['apple', 'banana', 'cherries', 'melon']
fruits.append("melon")
print(fruits)
cars = ["Maruti", "Ford"] ['Maruti', 'Ford', 'Honda', 'Hyundai']
cars.append("Honda")
cars.append("Hyundai")
print(cars)
#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']
Introduction to Python 253

