A python list is a collection data type that is ordered and changeable. Also, it allows duplicate members. It is the most frequently used collection data type used in Python programs. We will see how we can add an element to a list using the index feature.
But before adding the element in an existing link, let's access the elements in a list using the index feature.
Accessing List using Index
every element in the list is associated with an index and that is how the elements remain ordered. We can access the elements by looping through the indexes. The below program prints the elements at indices 1 and 2. The last index value is not included in the search.
Example
vowels_list = ['a','i','o', 'u'] print(vowels_list[1:3])
Running the above code gives us the following result:
['i', 'o']
Adding Element
We can also use the same concept to add the element at a particular index. In the below program we are adding the element at index position 1.
Example
vowels = ['a','i','o', 'u'] print("values before indexing are :",vowels) #index vowels.insert(1, 'e') print('\nafter adding the element at the index 1 is : ', vowels)
Running the above code gives us the following result:
values before indexing are : ['a', 'i', 'o', 'u'] after adding the element at the index 1 is : ['a', 'e', 'i', 'o', 'u']