how to add element at particular index in list python code example

Example 1: python append in specific position

# --> list.insert(position, element) <--

# List of string 
list1 = ['Hi' ,  'hello', 'at', 'this', 'there', 'from']

# Add an element at 3rd position in the list
list1.insert(3, 'why')
#-> ['Hi', 'hello', 'at', 'why', 'this', 'there', 'from']

Example 2: python add to list with index

list.insert(index, element)

Example 3: add element to list python at index

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")

Example 4: how to add item to a list python

my_list = []
item1 = "test1"
my_list.append(item1)

print(my_list) 
# prints the list ["test1"]

Example 5: how to insert an element to the end of the list using insert in python

Syntax : list(index, item)

>>> numbers = [1, 2, 3]
>>> numbers
[1, 2, 3]
>>> numbers.insert(len(numbers), 4) #len(list) as index to insert item at the end of list
>>> numbers
[1, 2, 3, 4]
>>> numbers.insert(4, 5)
>>> numbers
[1, 2, 3, 4, 5]
>>> len(numbers)
5
>>> numbers[4] # last index always will be len(list) - 1. Because index starts at 0.
5
>>> numbers[5] # Throws error since index no 4 is the last index with element 5.
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    numbers[5]
IndexError: list index out of range

Example 6: how to add an item to a list python

numbers = [1, 2, 3, 4]
numbers.append(10)
print(numbers)