Lists in Python

In [3]:
list=[1,2,3,'abc',True,[5,6,7]]
In [6]:
list
Out[6]:
[1, 2, 3, 'abc', True, [5, 6, 7]]

The list above contains 6 elements.
Lets see some of the functions we can use on lists

In [8]:
#Tells us a size of list
len(list)
Out[8]:
6
In [12]:
#Elements of list can be retrieved using index, index starts at 0
In [13]:
list[3]
Out[13]:
'abc'
In [4]:
#Here we are fetching element 0 of element 5
list[5][0]
Out[4]:
5

Adding elements to list can be done by either using append or extend

In [6]:
list.append([100,200,300])
In [8]:
# As you can see append adds the list as list at the end of the original list
list
Out[8]:
[1, 2, 3, 'abc', True, [5, 6, 7], [100, 200, 300]]
In [9]:
list.extend([100,200,300])
In [10]:
#Extend on the other hand will append these elements as individual elements
list
Out[10]:
[1, 2, 3, 'abc', True, [5, 6, 7], [100, 200, 300], 100, 200, 300]
In [11]:
#Creates a copy of list
list2=list.copy()
In [12]:
list2
Out[12]:
[1, 2, 3, 'abc', True, [5, 6, 7], [100, 200, 300], 100, 200, 300]
In [13]:
#Empties the list
list2.clear()
In [14]:
list2
Out[14]:
[]
In [15]:
#Removes the last element of list
list.pop()
Out[15]:
300
In [16]:
list
Out[16]:
[1, 2, 3, 'abc', True, [5, 6, 7], [100, 200, 300], 100, 200]
In [17]:
#Reverses the list
list.reverse()
In [18]:
list
Out[18]:
[200, 100, [100, 200, 300], [5, 6, 7], True, 'abc', 3, 2, 1]
In [20]:
#Counts the occurence of element
list3=[1,2,1,4,5]
list3.count(1)
Out[20]:
2
In [21]:
#Sorts the list
list3.sort()
In [22]:
list3
Out[22]:
[1, 1, 2, 4, 5]
In [26]:
#Inserts an element--In this case inserting 100 at index 5
list3.insert(5,100)
In [29]:
list3
Out[29]:
[1, 1, 2, 4, 5, 100]
In [30]:
#Delete an element at index 5
del list3[5]
In [31]:
list3
Out[31]:
[1, 1, 2, 4, 5]
In [32]:
#Remove an element 5
list3.remove(5)
In [33]:
list3
Out[33]:
[1, 1, 2, 4]
In [35]:
#Change the value at certain index in list
list3[0]=-1
In [37]:
list3
Out[37]:
[-1, 1, 2, 4]
In [38]:
#Returns the index of the element we are searching
list3.index(4)
Out[38]:
3