1.Methods on list

Making some list...

In [1]:
somelist = ['cat', 'mouse', 'elephant']



Append adds an element at the end of the list

In [2]:
somelist.append('starfish')
print(somelist)
['cat', 'mouse', 'elephant', 'starfish']



Insert can add the element at any index we specify

In [3]:
somelist.insert(1, 'lion')
print(somelist)
['cat', 'lion', 'mouse', 'elephant', 'starfish']



remove method removes the element given, irrespective of the index of that element in the list

In [4]:
somelist.remove('mouse')
print(somelist)
['cat', 'lion', 'elephant', 'starfish']

Keep in mind that remove method only removes one element, when it first encounters it

Illustrating this with example below

In [5]:
al = ['remove this','b','c','remove this','d','remove this']
In [6]:
al.remove('remove this')
al
Out[6]:
['b', 'c', 'remove this', 'd', 'remove this']

As you can see, it removed the element on it's first encounter which is from left to right.



Sort sorts the list, according to whether the list contains strings or numbers. Sort does not work on lists having both strings and integers.

In [7]:
numberlist = [2,4,5,3,5,6,7,5,4,2]
numberlist.sort()
numberlist
Out[7]:
[2, 2, 3, 4, 4, 5, 5, 5, 6, 7]

The capital letters come before small letters, as python uses 'ASCII-Betical' order, where capital letters all come before small letters

In [8]:
abclist = ['Cat','cat','dog','Dog','bat','Bat','tiger']
abclist.sort()
abclist
Out[8]:
['Bat', 'Cat', 'Dog', 'bat', 'cat', 'dog', 'tiger']

To sort in true alphabetical order, we do the following

In [9]:
abclist.sort(key=str.lower)
abclist
Out[9]:
['Bat', 'bat', 'Cat', 'cat', 'Dog', 'dog', 'tiger']



WARNING - We don't do something like following!

In [10]:
abclist = abclist.sort()

Methods have return value of None, so what the above code did, is that it assigned the None value to the abclist, vanishing the entire list!

In [11]:
print(abclist)
None