Advertisements
Advertisements
Question
What the different ways to insert an element in a list. Explain with a suitable example.
Advertisements
Solution
append() function in Python is used to add more elements to 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 the 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, the insert function inserts a new element ‘Ramakrishnan’ at the index value 3, i.e., at the 4th position. While inserting a new element in between the existing elements, at a particular location, the existing elements shift one position to the right.
APPEARS IN
RELATED QUESTIONS
If List = [10 ,20 ,30 ,40 ,50] then List[2] = 35 will result ______
If List = [17,23,41,10] then List.append(32) will result ______
Which of the following Python function can be used to add more than one element within an existing list?
Which of the following set operation includes all the elements that are in two sets but not the ones that are common to two sets?
What is a List in Python?
How will you access the list elements in reverse order?
What will be the output of the following code?
list = [2**x for x in range(5)]
print(list)
Explain the difference between del and clear( ) in the dictionary with an example.
What is the difference between List and Dictionary?
What is the purpose of range( )? Explain with an example.
