Container Data Structures

Methods

New items can be inserted into a specific position in the list by using the insert() function, which will not modify the existing items, but shift any items positioned at and after the specified index towards the end of the list:

temp = [1, 3, 5, 6, 7]

temp.insert(2, 15)

print(temp)

Output:

[1, 3, 15, 5, 6, 7]

New items can be added to the end of the lists by using the append() method:

temp = [1, 3, 5, 6, 7]

temp.append(17)

print(temp)

Output:

[1, 3, 5, 6, 7, 17]

Be careful when you append items to lists, as the following loop will never end:

mylist = [1]

for x in mylist:
    mylist.append(1)
    print("x")

Items in a set, tuple, or list can be appended to the end of another list by using the extend() method of that list:

temp = [1, 3, 5, 6, 7]

temp_set   = {10, 11, 12, 13}
temp_tuple = (20, 21, 22, 23, 24, 25)
temp_list  = [30, 31, 32, 33, 34]

temp.extend(temp_set)
temp.extend(temp_tuple[1:3])
temp.extend(temp_list[2:4])

print(temp)

Output:

[1, 3, 5, 6, 7, 10, 11, 12, 13, 21, 22, 32, 33] 

Lists and tuples can be joined together using the +operator:

colors_1 = ["black", "azure", "ruby", "orange", "blue", "violet", "pink" ]
colors_2 = ["red", "purple", "cyan"]
colors_merged = colors_1 + colors_2
print(colors_merged)

Output: ['black', 'azure', 'ruby', 'orange', 'blue', 'violet', 'pink', 'red', 'purple', 'cyan']


An item from the list can be removed from the list using the remove() method, which is going to remove the first occurrence of the item in the list:

temp = [1, 3, 5, 6, 3, 7]

temp.remove(3)

print(temp)

Output: [1, 5, 6, 3, 7]


The pop() method can be used to remove items using an index value. If no index is specified, then the last item in the list will be removed, hence the name suggests (hint: Stacks, push and pop). The method will return the item in addition to removing it from the list:

temp = [1, 3, 5, 6, 3, 7]

popped_item_value = temp.pop(3)

print(temp)
print(popped_item_value)

Output:

[1, 3, 5, 3, 7]
6

del keyword can be used to remove an element from the list or delete the list (or tuple) variable itself, making it inaccessible:

temp = [1, 3, 5, 6, 3, 7]
del temp[3]
print (temp)

del temp
print(temp)

Output:

[1, 3, 5, 3, 7]
Traceback (most recent call last):
  File ..., line 6, in <module>
    print(temp)
NameError: name 'temp' is not defined

All items in the list can be removed at once without deleting the list by using the clear() method:

temp = [1, 3, 5, 6, 3, 7]
print(temp)

temp.clear()
print(temp)

Output:

[1, 3, 5, 6, 3, 7]
[]