Everything About List's in Python

Published Mar 10, 2018Last updated May 22, 2018

To start anything about list in python we first need to create a list, so you open your python shell and type this in.


>>>example_list = []

There are lots of operations we can carry out on that empty list above they are called "list methods", you can see all list methods with just one function.

 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

As you can see there are a lot of methods but the one we really want to pay attention to are the ones without underscores.

The append method is used to add values to an existing list


Now we've added values to our  list if we want to check them we just call the list

[1, 2, 3, 5, 4, 6, 5]

The sort method sorts or arranges the list into ascending order  i.e. from smallest to largest, and we can sort our list by using the ".sort" method.

[1, 2, 3, 4, 5, 5, 6]  #the sorted output

Count method outputs an integer of the total number of times a given value appears in our list.

1 #the total number of times '1' appears in our list
2 #'5' appears two times in our list

This returns the first index of a value and it raises an error "ValueError" if the value isn't present.

1 #'1' is at index 0
4 #the first index of '5' is at 4

The insert method add a value to the list in a given index , its like the append but this time you specify the index you want it to be. the format is  "your_list.insert(index, value)".

>>>example_list.insert(0, 7)
[7, 1, 2, 3, 4, 5, 5, 6] #we've added '7' at index 0

This method removes the first occurrence of a given value.

[1, 2, 3, 4, 5, 5, 6] #we removed '7' from the list.


the pop method removes the value at a given index, with the last index being the 'default'.

6 #removes '6' because its the last
[1, 2, 3, 4, 5, 5,]
3 #removes the value at index 2
[1, 2, 4, 5, 5,]

This reverses or flips the list.

[5, 5, 4, 2, 1]

This method extends a list with another iterable type i.e. A list, tuple or dictionary.

>>>another_list = [7, 8, 9] #we create another list
[5, 5, 4, 2, 1, 7, 8, 9] #example_list has been extended
we can also extend with a tuple

>>>a_tuple = (10, 11, 12) #we create a tuple
[5, 5, 4, 2, 1, 7, 8, 9, 10, 11, 12] #example_list has been extended
Discover and read more posts from kelvin paschal
get started