Nested lists

ListsΒ 
canΒ 
beΒ 
includedΒ 
within
Β 
theΒ 
mainΒ 
bigΒ 
listΒ 
asΒ 
anΒ 
elementΒ 
ofΒ 
theΒ 
mainΒ 
list.
TheseΒ 
innerΒ 
listsΒ 
areΒ 
calledΒ 
"sub-lists"
.
list_name=[item1,[item21,item22,item23],item3,item4]
num_list = [1, 2, [3, 4]]
print(num_list)

Indexing in Nested List

IfΒ 
weΒ 
wantΒ 
anΒ 
itemΒ 
withinΒ 
theΒ 
nestedΒ 
listΒ 
orΒ 
sublistΒ 
ofΒ 
theΒ 
list,Β 
weΒ 
addΒ 
theΒ 
indexΒ 
ofΒ 
theΒ 
itemΒ 
inΒ 
theΒ 
sublistΒ 
(containingΒ 
theΒ 
item)Β 
alongΒ 
withΒ 
theΒ 
nestedΒ 
list/sublistΒ 
indexΒ 
number.
list_name[index of sublist containing the item][index of the item in that sublist]
num_list = [1, 2, [3, 4]]
print(num_list[2][0])

list_num = [1, 2, [3, [4, 5]]]
print(list_num[2][1][1])

Adding, Replacing or Deleting values by slicing

NestedΒ 
listsΒ 
canΒ 
beΒ 
added
Β 
orΒ 
changed
Β 
withinΒ 
aΒ 
listΒ 
byΒ 
slicingΒ 
withΒ 
theΒ 
givenΒ 
indices.
#Adding an element to the list using slicing
list_name[starting_index:starting_index]=[value]
WeΒ 
canΒ 
replaceΒ 
moreΒ 
thanΒ 
oneΒ 
elementΒ 
inΒ 
oneΒ 
go.
WeΒ 
canΒ 
alsoΒ 
replaceΒ 
2Β 
orΒ 
moreΒ 
elementsΒ 
withΒ 
aΒ 
lesserΒ 
numberΒ 
ofΒ 
elements.
list_name[starting_index:ending_index]=[[value1,value2,...]]
ElementsΒ 
canΒ 
alsoΒ 
beΒ 
removedΒ 
fromΒ 
aΒ 
listΒ 
withΒ 
theΒ 
helpΒ 
ofΒ 
slicing.
list_name[starting_index:ending_index]=[]
a = [1, 2, 5, 6]
a[2:2] = [[3, 4]]
#The list [3,4] gets added between the 2nd and 3rd element
print(a)

a = [1, 2, 5, 6]
a[2] = [3, 4]
print(a)

a = [1, 2, 3, 4, 5]
a[1:3] = ['a','b']
print(a)

a = [1, 2, 3, 4, 5]
a[1:3] = ['a']
print(a)

a = [1, 2, 3, 4, 5]
a[1:3] = []
print(a)