How to add Item into the List
Let's suppose the list is ['a', 'b', 'c', 'b'], I want to insert a new Item 'B' at the place of index 2, Below is the simplest ways to add and enhance your coding skill.
First ways:
When you use the slice assignment l[2:2] = 'B' on a list in Python, you are inserting the elements of the iterable 'B' into the list at index 2. Since the string 'B' is an iterable containing a single character 'B', it will insert the character 'B' at the specified index.
l = ['a', 'b', 'c', 'a', 'b']
l[2:2] = 'B'
⇣ at index 2
print(l) # ['a', 'b', 'B', 'c', 'a', 'b']
Second Way:
By the use of the insert() method
l2 = ['a', 'b', 'c', 'a', 'b']
l2.insert(2,'C')
⇣ at index 2
print(l2) # ['a', 'b', 'B', 'c', 'a', 'b']
Comments
Post a Comment