The Elegant and Effective Way to Modify a List
In the Python programming language, you can prepend an element to a list using the append() method. But before we proceed, let’s understand that there is another way of inserting elements at the start …
In the Python programming language, you can prepend an element to a list using the append() method. But before we proceed, let’s understand that there is another way of inserting elements at the start of the list in python known as prepend or insert method. Here is how it is done
# Creating a list named fruits
fruits = ['banana', 'apple', 'mango']
# Prepending new element to list using insert() function
fruits.insert(0, 'cherry')
print(fruits) # prints ['cherry', 'banana', 'apple', 'mango']
Here insert()
method inserts an item at a specific position in the list. The first parameter is the index where you want to insert your element and the second one is the actual element that you are inserting into the list.
In this code, we used the insert()
function to add ‘cherry’ at the beginning of our list ‘fruits’. This gives us a new list in which ‘cherry’ is at the front while ‘banana’, ‘apple’, and ‘mango’ remain as they were.
This method not only helps in keeping track of elements but also provides flexibility to insert an element at any index. It makes code more dynamic, readable and understandable making it a highly effective programming approach.