1.

What the different ways to insert an element in a list. Explain with suitable example. Inserting elements in a list?

Answer»

append( ) function in Python is used to add more elements in a list. But, it includes elements at the end of a list. If you want to include an element at your desired position, you can use insert () function is used to insert an element at any position of a list.

Syntax:

List, insert (position index, element)

Example:

>>> MyList=[34,98,47, ‘Kannan’ , ‘Gowrisankar’ , ‘Lenin’ , ‘Sreenivasan’ ]

>>> print(MyList)

[34, 98, 47, ‘Kannan’ , ‘Gowrisankar’ , ‘Lenin’ , ‘Sreenivasan’]

>>> MyList.insert(3, ‘Ramakrishnan’)

>>> print(MyList)

[34, 98, 47, ‘Ramakrishnan’ , ‘Kannan’ , ‘Gowrisankar’ , ‘Lenin’ , ‘Sreenivasan’]

In the above example, insertf) function inserts a new element ‘Ramakrishnan’ at the index value 3, ie. at the 4th position. While inserting a new element in between the existing elements, at a particular location, the existing elements shifts one position to the right.



Discussion

No Comment Found