A Few List Methods
I hate reading reference manuals. They bug me to no end and I generally do not get beyond page number 10. These excellent habits of mine were the main reason for my taking up this task. I decided to brush up on my knowledge of Python’s built-in sequence-types and of course, since I love using lists in most of my code, I will attempt to write down some of the List methods in Python. I am not too sure if the same algorithms are used in Python but these work. Well, here goes:
First comes the very familiar append() method.
Usage: some_list.append(element)
#Author: Shriphani Palakodety
def append(list_name, element):
list_name[len(list_name):] = element
>>> list_name = [1,2,3] >>> list_name.append(4) >>> print list_name [1, 2, 3, 4] >>>
Next comes the extend() method. This method takes a list as an argument and appends its elements to the current list.
list_name[len(list_name):] = list_to_add
A bunch of no-brainer methods follow. They are:
def insert(list_name, position, element):
list_name = list_name[0:position] + [element] + list_name[position+1:]
#index(element) - return the index of the first item whose value
#is equal to the supplied argument
def index(list_name, element):
for i in range(len(list_name)):
if list_name[i] == element:
break
return i
else:
continue
return "Element doesn’t exist"
#remove(element) - remove first item from list whose value is "element"
def remove(list_name, element):
position = list_name.index(element)
list_name = list_name[0:position] + list_name[position+1:]
The next method is the count() method. The count method returns the number of times an element has been repeated in a list. This is what I wrote in a few seconds:
freq_dict = {}
index = 0
freq_dict[element] = 0
for i in range(len(list_name)):
if list_name[i] == element:
freq_dict[element] += 1
else:
continue
return freq_dict[element]
That is the count() method. Finally, we have the reverse() method. When used, it reverses all the elements in a list.
new_list = copy.copy(list_name)
for i in range(len(new_list)):
list_name[i] = new_list[len(new_list)-1 - i]
That session served me quite well. I got to write some code and also got myself to read the reference manual.
Well, Happy Coding ! ![]()



2 comments
For reversing lists, look at the inbuilt rev() function. Another cool way to do it is to use list_name[::-1].
P.S: Your blog’s comment template is broken
Thanks for the comments. I seem to notice nothing odd about my blog’s comment template though.
Leave a Comment