Chapter 7. Data Structures
>>> a = [23, 45, 1, -3434, 43624356, 234]
>>> a.append(45)
>>> a
[23, 45, 1, -3434, 43624356, 234, 45]
At first we created a list
a. Then to add
45 at the end of the list we call
a.append(45) method. You can see that
45 added at the end of the list. Sometimes it may require to insert data at any place within the list, for that we have
insert() method.
>>> a.insert(0, 1) # 1 added at the 0th position of the list
>>> a
[1, 23, 45, 1, -3434, 43624356, 234, 45]
>>> a.insert(0, 111)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 234, 45]
count(s) will return you number of times
s is in the list. Here we are going to check how many times
45 is there in the list.
>>> a.count(45)
2
If you want to any particular value from the list you have to use
remove() method.
>>> a.remove(234)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 45]
Now to reverse the whole list
>>> a.reverse()
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111]
We can store anything in the list, so first we are going to add another list
b in
a , then we will learn how to add the values of
b into
a .
>>> b = [45, 56, 90]
>>> a.append(b)
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90]]
>>> a[-1]
[45, 56, 90]
>>> a.extend(b) #To add the values of b not the b itself
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90], 45, 56, 90]
>>> a[-1]
90
Above you can see how we used
a.extend() method to extend the list. To sort any list we have
sort() method.
>>> a.sort()
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356, [45, 56, 90]]
You can also delete element at any particular position of the list using the del keyword.
>>> del a[-1]
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356]