xxxxxxxxxx
# to add an item to a list
list.append(item)
# to insert into a list
list.insert(int, element)
xxxxxxxxxx
# list.append(x): add an item to the end
list_1 = ['A', 'B', 'C']
list_1.append('D') # -> ["A", "B", "C", "D"]
# list.insert(i, x): insert an item at a given position
list_2 = ['A', 'B', 'D']
list_2.insert(2, 'C') # -> ["A", "B", "C", "D"]
# list.extend(iterable): appending all items from an iterable
list_3 = ['A', 'B', 'C']
list_4 = ['D', 'E', 'F']
list_3.extend(list_4) # -> ['A', 'B', 'C', 'D', 'E', 'F']
xxxxxxxxxx
# list.insert(before, value)
list = ["a", "b"]
list.insert(1, "c")
print(list) # ['a', 'c', 'b']
xxxxxxxxxx
letters = ["a", "b", "c", "d"]
# Add
letters.append("e") #Output: ['a', 'b', 'c', 'd', 'e']
letters.insert(0, "-") #Output ['-', 'a', 'b', 'c', 'd', 'e']
xxxxxxxxxx
# to add an item to a list
list.append(item)
# To extend an list with a new list
list1.extend(list2)
xxxxxxxxxx
# create a list of vowels
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 (4th position)
vowel.insert(3, 'o')
print('List:', vowel)
# Output: List: ['a', 'e', 'i', 'o', 'u']
xxxxxxxxxx
l = list(range(3))
print(l)
# [0, 1, 2]
l.insert(0, 100)
print(l)
# [100, 0, 1, 2]
l.insert(-1, 200)
print(l)
# [100, 0, 1, 200, 2]
xxxxxxxxxx
#add item to the beginning of list – at index 0
clouds = [‘Cisco’, ‘AWS’, ‘IBM’]
clouds.insert(0, ‘Google’)
print(clouds)
[‘Google’, ‘Cisco’, ‘AWS’, ‘IBM’]
#add item to the end of list
a.insert(len(a),x) is equivalent to a.append(x)
clouds = [‘Cisco’, ‘AWS’, ‘IBM’]
clouds.insert(len(clouds), ‘Google’)
print(clouds)
[‘Google’, ‘Cisco’, ‘AWS’, ‘IBM’]
#add item to specific index
number_list = [10, 20, 40] # Missing 30.
number_list.insert(2, 30 ) # At index 2 (third), insert 30.
print(number_list) # Prints [10, 20, 30, 40]
number_list.insert(100, 33)
print(number_list) # Prints [10, 20, 30, 40, 33]
number_list.insert(-100, 44)
print(number_list) # Prints [44, 10, 20, 30, 40, 33]
xxxxxxxxxx
fruits = ["Apple", "Banana"]
# 1. append()
print(f'Current Fruits List {fruits}')
f = input("Please enter a fruit name:\n")
fruits.append(f)
print(f'Updated Fruits List {fruits}')